Find a course

Module 4: Arrays and ObjectsLesson 8 of 1214 min

Transforming Data with map, filter and reduce

Use map, filter, reduce, find and sort to transform lists without manual loops, and avoid the default sort trap with numbers.

Step 1 of 14Learn

Loops you no longer have to write

Most array loops fall into a few patterns: transform every item, keep some items, or combine all items into one value. JavaScript has a method for each, and they make code shorter and clearer. Each takes a callback function that is called once per item.

map transforms every item and returns a new array of the same length:

const prices = [10, 25, 40];
const withTax = prices.map(p => p * 1.08);
// [10.8, 27, 43.2]

filter keeps the items for which the callback returns true, and returns a new, possibly shorter array:

const scores = [55, 82, 91, 47, 76];
const passing = scores.filter(s => s >= 60);
// [82, 91, 76]

Neither method changes the original array. That makes them safe to use: prices still holds [10, 25, 40].

The callback can also receive the index as a second argument: names.map((name, i) => (i + 1) + ". " + name) numbers a list.

You can chain them, reading top to bottom like a recipe:

const total = orders
  .filter(o => o.status === "paid")
  .map(o => o.amount);

A common mistake is forgetting to return inside a braces-style callback: prices.map(p => { p * 2 }) produces an array of undefined values.

Step 2 of 14Compare

map, filter and reduce at a glance

Aspectmapfilterreduce
Callback returnsThe new itemtrue or falseThe new running result
ResultNew arrayNew arrayOne value (any type)
Result lengthSame as inputSame or shorterNot an array
Exampleprices.map(p => p * 2)scores.filter(s => s >= 60)cart.reduce((t, p) => t + p, 0)

Step 3 of 14Practice · Choose one

What is the result of [3, 8, 1, 6].filter(n => n > 4).map(n => n * 10)?

Step 4 of 14Learn

reduce: boil a list down to one value

reduce combines all items into a single value: a sum, a maximum, a count, even an object. It is the accumulator pattern in one method:

const cart = [12.5, 30, 7.5];
const total = cart.reduce((sum, price) => sum + price, 0);
// 50

The callback receives the accumulator (sum, the running result) and the current item (price). Whatever the callback returns becomes the accumulator for the next item. The second argument to reduce, 0, is the starting value.

Step by step: sum starts at 0; 0 + 12.5 = 12.5; 12.5 + 30 = 42.5; 42.5 + 7.5 = 50.

Always pass the starting value. Without it, reduce uses the first item as the start, which works for sums of numbers but throws an error on an empty array and gives surprising results when the items are objects.

Two relatives finish the toolkit:

  • find returns the first item that matches, or undefined: users.find(u => u.id === 7).
  • some and every return booleans: does at least one item match, or do all of them? scores.every(s => s >= 60) checks whether everyone passed.

Use the most specific method: find when you need one item, some when you need a yes/no, filter when you need all matches.

Step 5 of 14Practice · Chart

reduce, one item at a time: the running total

After which item does the accumulator first go above $40?

Tap the bar that answers the question, then press Check.

reduce, one item at a time: the running totalBar chart with 4 categories: Start (0): $0; + 12.5: $12.5; + 30: $42.5; + 7.5: $50.$0$10$20$30$40$50Start (0)+ 12.5+ 30+ 7.5$0$12.5$42.5$50
cart = [12.5, 30, 7.5]; reduce((sum, price) => sum + price, 0).
reduce, one item at a time: the running total
Itemaccumulator
Start (0)$0
+ 12.5$12.5
+ 30$42.5
+ 7.5$50

Step 6 of 14Practice · Code challenge

Write a function totalPrice(prices) that uses reduce to return the sum of an array of numbers. An empty array should return 0.

Runs in a sandbox in your browser.
  • totalPrice([12.5, 30, 7.5])
  • totalPrice([1, 2, 3, 4])
  • totalPrice([])

Step 7 of 14Practice · Match the pairs

Match each goal to the best array method.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Get a new array with every price doubled
  2. Keep only the orders over $100
  3. Add up all the order totals
  4. Get the first user whose email matches
  5. Check whether any item is out of stock

Step 8 of 14Note

Step 9 of 14Learn

Sorting, and the trap inside it

sort reorders an array in place (it changes the original) and also returns it. With strings it does what you expect:

["pear", "apple", "fig"].sort(); // ["apple", "fig", "pear"]

With numbers, the default is a trap:

[10, 1, 5, 100, 25].sort(); // [1, 10, 100, 25, 5]  (!)

By default, sort converts items to strings and compares them character by character, so "100" comes before "25" because "1" comes before "2". To sort numbers, pass a compare function:

nums.sort((a, b) => a - b); // ascending: [1, 5, 10, 25, 100]
nums.sort((a, b) => b - a); // descending

The compare function returns a negative number if a should come first, a positive number if b should come first, and 0 if they are equal. Subtracting does exactly that for numbers.

To sort objects, compare a property: products.sort((a, b) => a.price - b.price). For text, use a.name.localeCompare(b.name), which handles accents and capitals sensibly.

Because sort changes the original array, copy it first when you need to keep the original order: [...nums].sort((a, b) => a - b) or the newer nums.toSorted((a, b) => a - b).

Step 10 of 14Practice · True or false

[9, 80, 700].sort() returns [9, 80, 700].

Step 11 of 14Note

Step 12 of 14Diagram

The top-3 pipeline, stage by stage

The top-3 pipeline, stage by stageProcess diagram: students (all) → filter: grade >= 70 → sort: highest first → slice(0, 3) → map: s => s.name.students (all)filter: grade >= 70sort: highest firstslice(0, 3)map: s => s.name

Tap a shape with to see more.

students (all)

The original array is never changed by filter, slice or map.

filter: grade >= 70

Keeps passing students only.

sort: highest first

(a, b) => b.grade - a.grade. sort works on the new filtered array.

slice(0, 3)

Takes the first three items.

map: s => s.name

Turns objects into an array of names.

Step 13 of 14Note

Step 14 of 14Practice · Code challenge

Write a function passingNames(students) that takes an array of objects like { name: "Ana", score: 82 } and returns an array of the names of students who scored 60 or more, in their original order.

Runs in a sandbox in your browser.
  • passingNames([{ name: "Ana", score: 82 }, { name: "Ben", score: 45 }, { name: "Cy", score: 60 }])
  • passingNames([{ name: "Dee", score: 10 }])