Lesson 21 of 28
In progress
map, filter and reduce
Transform, select, search and total data with the array methods you will use every day, and sort without surprises.
Most loops over data do one of five things: transform each item, keep some items, find one, test the collection, or produce a single value. Each has a method, and naming the intent makes the code shorter and easier to review.
What you will learn
- Transform with
mapand select withfilter. - Test with
some,everyandfind. - Total with
reduceand sort with a correct comparator.
map
Editable. Runs in your browser.
console.log(withTax);
console.log(prices);
Press Run to see the output.
map returns a new array of the same length, leaving the original unchanged. The callback receives the item, its index and the array, though most callbacks only need the item.
Use map when you want the results. forEach is for side effects and returns undefined, so assigning its result is always a bug.
filter
Editable. Runs in your browser.
const available = products.filter((item) => item.stock > 0);
console.log(available.map((item) => item.name));
Press Run to see the output.
The callback returns a boolean. filter keeps the items where it returned true, and the result may be shorter or empty. Chaining filter then map is a common and readable shape.
find, some, every
Editable. Runs in your browser.
console.log(items.find((item) => item.id === 2));
console.log(items.some((item) => item.done));
console.log(items.every((item) => item.done));
console.log(items.findIndex((item) => item.id === 2));
Press Run to see the output.
find returns the first match or undefined. some answers "does at least one match", and every answers "do all match". findIndex gives the position, which is what you need before replacing an item.
every on an empty array returns true, which is logically consistent and occasionally surprising. If the list must be non-empty, check the length first.
reduce
Editable. Runs in your browser.
const paidTotal = orders.reduce((sum, order) => {
return order.paid ? sum + order.total : sum;
}, 0);
console.log(paidTotal);
Press Run to see the output.
The callback receives the accumulator and the current item. The second argument is the starting accumulator, and it should almost always be supplied: without it, the first item becomes the accumulator, which breaks on empty arrays and on objects.
reduce can build objects too:
Editable. Runs in your browser.
console.log(byCustomer);
Press Run to see the output.
That is powerful and easy to overuse. If a reduce needs a paragraph to explain, a for...of loop with a named accumulator is usually kinder to the next reader.
sort and toSorted
Editable. Runs in your browser.
console.log([…scores].sort());
console.log([…scores].sort((a, b) => a – b));
console.log([…scores].sort((a, b) => b – a));
Press Run to see the output.
sort converts items to strings by default, so 100 comes before 72 in the first line. Always pass a comparator for numbers. sort mutates in place; toSorted returns a copy, and is the safer default in modern code.
For objects, compare a chosen field: items.sort((a, b) => a.name.localeCompare(b.name)). localeCompare handles accents and case better than <.
Sorting is stable, so equal items keep their relative order. To sort by two keys, compare the first and fall back to the second.
Flattening
flat() turns nested arrays into one level, and flatMap() maps and flattens in one pass. Both are useful for lists of lists, such as search results grouped by category.
Editable. Runs in your browser.
Press Run to see the output.
flat() defaults to one level; pass a depth for deeper nesting. flatMap is not a general replacement for map followed by flat when the callback returns a single value, because that value is not flattened further.
Choosing the method
| Goal | Method |
|---|---|
| Transform every item | map |
| Keep matching items | filter |
| Find one item | find |
| Test the collection | some, every |
| Produce one value | reduce |
| Order items | sort / toSorted |
If you need to stop early, a for...of loop with break is still the right tool.
items.sort() on an array of numbers sorts them as text, so [1, 10, 2] becomes [1, 10, 2] and [72, 100, 88] becomes [100, 72, 88]. Pass (a, b) => a - b for ascending numeric order, every time.
Given an array of students with name and score, produce the names of those above 80, sorted alphabetically, and the average score of the whole class. Use filter, sort and reduce.
Show solution
Editable. Runs in your browser.
const names = students
.filter((student) => student.score > 80)
.map((student) => student.name)
.sort((a, b) => a.localeCompare(b));
const average = students.reduce((sum, student) => sum + student.score, 0) / students.length;
console.log(names);
console.log(Math.round(average));
Press Run to see the output.
Filtering before mapping avoids work, and sorting names uses localeCompare rather than the default string comparison. The average divides once at the end, after the reduce has summed the scores.
Recap
map,filter,findandreducename the intent and avoid manual accumulators.- Always give
reducean initial value andsorta numeric comparator. - Reach for a loop when you need to stop early or the reduce becomes hard to read.
Next, you will split code into modules so files can share functions without globals.
Which is faster, a loop or map?
Can I chain filter and map?
Progress is saved in this browser only. No account, no email.