Sub topic 8
Transforming Data with map, filter, and reduce
This chapter assumes you know arrow functions, the idea of higher-order functions from the previous chapter, and how to avoid mutation with spread syntax. Here we use the three array methods that do most of the everyday data work in functional JavaScript.
The working model
Each method takes a callback and returns a new value. None of them changes the original array.
| Method | Callback returns | Result | Length of result |
|---|---|---|---|
| `filter` | `true` or `false` | New array of the items that passed | Same or shorter |
| `map` | A new item | New array of transformed items | Always the same |
| `reduce` | The updated accumulator | Any single value | Not an array, unless you build one |
An imperative loop mixes three jobs: choosing items, changing them, and combining them. Each of these methods does one of those jobs, so a chain of them reads like a description of the result you want.
From loop to chain
Here is the imperative version of "total revenue from paid orders":
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 15, paid: false },
{ id: 3, total: 60, paid: true }
];
let revenueLoop = 0;
for (let i = 0; i < orders.length; i++) {
if (orders[i].paid) {
revenueLoop += orders[i].total;
}
}
console.log(revenueLoop); // 100The declarative version splits that work into named steps:
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 15, paid: false },
{ id: 3, total: 60, paid: true }
];
const revenue = orders
.filter((o) => o.paid)
.map((o) => o.total)
.reduce((sum, t) => sum + t, 0);
console.log(revenue); // 100
console.log(orders.length); // 3, original untouchedHow reduce works
reduce calls your callback once per item. It passes in the accumulator, which is the result so far, and the current item. Whatever the callback returns becomes the accumulator for the next call. The second argument to reduce sets the starting accumulator.
reduce can build any shape, including objects:
const words = ['apple', 'avocado', 'banana', 'cherry', 'blueberry'];
const byLetter = words.reduce((groups, word) => {
const key = word[0];
return { ...groups, [key]: [...(groups[key] ?? []), word] };
}, {});
console.log(byLetter);
// { a: [ 'apple', 'avocado' ], b: [ 'banana', 'blueberry' ], c: [ 'cherry' ] }Common errors
- Missing initial value.
[].reduce((a, b) => a + b)throwsTypeError: Reduce of empty array with no initial value. Always pass a starting value. - Forgetting
returnin a block body.xs.map((x) => { x * 2 })gives an array ofundefined. Either drop the braces or addreturn. - Using
mapfor side effects. If you only want to log or save each item, useforEach.mapbuilds an array you then throw away. - Mutating items inside the callback.
users.map((u) => { u.active = true; return u; })changes the originals. Return{ ...u, active: true }instead. - Passing functions with extra parameters.
['1', '2', '3'].map(parseInt)returns[1, NaN, NaN]becausemappasses the index asparseInt's radix. Write.map((s) => parseInt(s, 10)).
Exercise
Given const users = [{ name: 'Ada', age: 36, active: true }, { name: 'Bo', age: 17, active: true }, { name: 'Cy', age: 52, active: false }], write one chain that returns the average age of active users who are 18 or older.
Show answer
const adults = users.filter((u) => u.active && u.age >= 18); const avg = adults.map((u) => u.age).reduce((s, a) => s + a, 0) / adults.length; gives 36. Keep adults in its own variable so you can divide by its length, and guard against an empty list if that can happen in your data.
Exercise
Why does [1, 2, 3].map((n) => { n * 10 }) return [undefined, undefined, undefined], and how do you fix it?
Show answer
Braces make the arrow body a block. A block returns nothing unless it has an explicit return. Write (n) => n * 10 or (n) => { return n * 10; }.