Sub topic 8
Transforming Data with map, filter, and reduce
This chapter assumes you know arrow functions, spread syntax, and the idea of a higher-order function: a function that takes or returns another function. It also assumes you are comfortable copying data instead of mutating it, as covered in the chapter on working without mutation. Every example runs in Node.js 18 or later, except where a newer version is named.
The working model
map, filter, and reduce are array methods that take a callback and return a new value. None of them changes the original array. Each one answers a different question.
| Method | Question it answers | Callback returns | Result |
|---|---|---|---|
| `map` | "What does each item become?" | The new item | Array of the same length |
| `filter` | "Which items do I keep?" | `true` or `false` | Array of the same or shorter length |
| `reduce` | "How do all items combine into one value?" | The next accumulator | Any single value |
A loop mixes three concerns: walking the array, deciding what to do with each item, and collecting the results. These methods do the walking and collecting for you. You write only the decision, as a small function. That is what "declarative" means here. You describe the result you want, and the method handles the steps.
const orders = [
{ id: 1, customer: 'ada', total: 40, paid: true },
{ id: 2, customer: 'bob', total: 15, paid: false },
{ id: 3, customer: 'ada', total: 60, paid: true },
{ id: 4, customer: 'cy', total: 25, paid: true }
];
// Imperative version
let revenueLoop = 0;
for (let i = 0; i < orders.length; i++) {
if (orders[i].paid) {
revenueLoop += orders[i].total;
}
}
// Declarative version
const revenue = orders
.filter((o) => o.paid)
.map((o) => o.total)
.reduce((sum, t) => sum + t, 0);
console.log(revenueLoop, revenue); // 125 125The full callback signature
All three methods pass more than the current item to the callback. map and filter call callback(item, index, array). reduce calls callback(accumulator, item, index, array). You rarely need the extra arguments, but they exist, and they cause one of the best-known bugs in JavaScript.
console.log(['10', '10', '10'].map(parseInt)); // [ 10, NaN, 2 ]
console.log(['10', '10', '10'].map((s) => parseInt(s, 10))); // [ 10, 10, 10 ]
console.log(['10', '10', '10'].map(Number)); // [ 10, 10, 10 ]parseInt takes a second parameter, the radix. map passes the index as that second argument. So the calls become parseInt('10', 0), parseInt('10', 1), and parseInt('10', 2). Radix 1 is invalid and gives NaN, and '10' in binary is 2.
reduce in depth
reduce is the general-purpose method. You can write map and filter in terms of it, but the reverse is not possible. The accumulator can be a number, a string, an object, an array, or a Map.
Always pass an initial value
Without an initial value, reduce uses the first element as the accumulator and starts at the second element. That works for sums of non-empty arrays. It throws on empty arrays, and it gives wrong results when the accumulator has a different type than the items.
const empty = [];
try {
empty.reduce((a, b) => a + b);
} catch (err) {
console.log(err.constructor.name); // TypeError
}
console.log(empty.reduce((a, b) => a + b, 0)); // 0
// Type mismatch without an initial value:
const items = [{ qty: 2 }, { qty: 3 }];
console.log(items.reduce((sum, it) => sum + it.qty)); // "[object Object]3"
console.log(items.reduce((sum, it) => sum + it.qty, 0)); // 5In the mismatched case, the first accumulator is the object { qty: 2 }. Adding a number to an object converts the object to a string.
Building objects with reduce
A common task is turning an array into a lookup table or a set of groups.
const orders = [
{ id: 1, customer: 'ada', total: 40 },
{ id: 2, customer: 'bob', total: 15 },
{ id: 3, customer: 'ada', total: 60 }
];
// Index by id
const byId = orders.reduce((acc, o) => ({ ...acc, [o.id]: o }), {});
console.log(byId[3].total); // 60
// Total spent per customer
const spend = orders.reduce((acc, o) => {
acc[o.customer] = (acc[o.customer] ?? 0) + o.total;
return acc;
}, {});
console.log(spend); // { ada: 100, bob: 15 }The byId version copies the accumulator on every step. That is fully immutable, but it costs O(n²) time, because each spread copies all the keys added so far. On a few hundred items you will not notice. On 100,000 items it can take seconds.
The spend version mutates the accumulator. This is acceptable when the accumulator is a fresh object created by the initial value {}, because no code outside the reduce call can see it change. The function as a whole stays pure. Do not mutate an accumulator that was passed in from outside, and never mutate the items themselves.
Related methods worth knowing
Many reduce calls are better written with a more specific method. The specific method states your intent and often stops early.
| Need | Method | Stops early? |
|---|---|---|
| First matching item | `find` / `findLast` | Yes |
| Does any item match? | `some` | Yes |
| Do all items match? | `every` | Yes |
| Map each item to zero or more items | `flatMap` | No |
| Run a side effect per item | `forEach` | No |
const carts = [
{ user: 'ada', items: ['pen', 'ink'] },
{ user: 'bob', items: [] },
{ user: 'cy', items: ['pad'] }
];
console.log(carts.flatMap((c) => c.items)); // [ 'pen', 'ink', 'pad' ]
console.log(carts.some((c) => c.items.length === 0)); // true
console.log(carts.every((c) => c.user.length > 1)); // true
console.log(carts.find((c) => c.user === 'cy').items); // [ 'pad' ]flatMap also works as a combined filter and map. Return [] to drop an item and [value] to keep a transformed one.
Common errors
Forgetting to return from a block body
An arrow function with braces needs an explicit return. Without it, the callback returns undefined.
const nums = [1, 2, 3];
console.log(nums.map((n) => { n * 2; })); // [ undefined, undefined, undefined ]
console.log(nums.map((n) => n * 2)); // [ 2, 4, 6 ]
console.log(nums.map((n) => ({ value: n }))); // object literal needs parenthesesIn reduce, a missing return makes the accumulator undefined on the next step, which usually fails one call later with a confusing error.
Using map for side effects
If you ignore the array that map returns, you wanted forEach or a for...of loop. Using map for logging or saving data builds an array you never use, and it tells readers the wrong thing about your intent.
Mutating items inside map
map returns a new array, but the items in it can be the same objects as before. This code changes the original orders:
const orders = [{ id: 1, total: 40 }];
const bad = orders.map((o) => { o.total *= 1.2; return o; });
console.log(orders[0].total); // 48 (original changed)
const source = [{ id: 1, total: 40 }];
const good = source.map((o) => ({ ...o, total: o.total * 1.2 }));
console.log(source[0].total, good[0].total); // 40 48Sparse arrays
map, filter, reduce, and forEach skip holes in sparse arrays. Array(3).map(() => 0) returns [ <3 empty items> ], not [0, 0, 0]. Use Array.from({ length: 3 }, () => 0) instead.
Performance: chains versus one pass
Each method in a chain walks the whole array and allocates a new one. filter().map().reduce() makes three passes and two intermediate arrays. For arrays up to tens of thousands of items, the cost rarely matters, and the readable chain is the better choice. When profiling shows a hot path, fold the steps into a single reduce or a loop:
const orders = [
{ total: 40, paid: true },
{ total: 15, paid: false },
{ total: 60, paid: true }
];
const revenue = orders.reduce((sum, o) => (o.paid ? sum + o.total : sum), 0);
console.log(revenue); // 100Measure before you make this change. You give up some readability to get the speed. The chapter on lazy sequences shows another way to avoid intermediate arrays.
Exercise
Given const words = ['apple', 'bob', 'kayak', 'tree', 'level'];, write a single expression using filter and map that returns the palindromes in upper case. A palindrome reads the same backward as forward.
Show answer
words.filter((w) => w === [...w].reverse().join('')).map((w) => w.toUpperCase()) returns [ 'BOB', 'KAYAK', 'LEVEL' ]. The spread [...w] makes a new array, so reverse mutates only that copy and leaves the string alone. On Node 20+ you could write [...w].toReversed().join('') instead.
Exercise
Why does [[1, 2], [3]].reduce((acc, xs) => acc.concat(xs)) work, while [].reduce((acc, xs) => acc.concat(xs)) throws? Fix it, and name a built-in method that does the same job.
Show answer
Without an initial value, reduce uses the first element as the accumulator, so the first call works because [1, 2] is an array. An empty array has no first element, so reduce throws a TypeError. Passing [] as the initial value fixes both cases: xs.reduce((acc, ys) => acc.concat(ys), []). The built-in equivalent is xs.flat(), or xs.flatMap((ys) => ys).
Exercise
Using reduce, count how many times each letter appears in the string 'banana', returning an object like { b: 1, a: 3, n: 2 }. Is it acceptable to mutate the accumulator here?
Show answer
[...'banana'].reduce((acc, ch) => { acc[ch] = (acc[ch] ?? 0) + 1; return acc; }, {}). Mutating is acceptable because the accumulator is a new object created by the initial value {}. No outside code can see it change, so the expression as a whole stays pure.