Sub topic 2
reduce: Folding an Array into One Value
This chapter assumes you already know map and filter, arrow functions, and how callbacks receive their arguments.
How reduce Works
reduce carries an accumulator through the array. For each element, it calls your callback as (acc, element, index, array). Whatever the callback returns becomes the next acc. After the last element, reduce returns the final accumulator.
const total = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0);
console.log(total); // 10| Step | acc | n | returned |
|---|---|---|---|
| 1 | 0 | 1 | 1 |
| 2 | 1 | 2 | 3 |
| 3 | 3 | 3 | 6 |
| 4 | 6 | 4 | 10 |
The callback must return the accumulator on every call. If you forget the return in a block-bodied arrow function, acc becomes undefined on the next step.
Choosing an Initial Value and Handling Empty Arrays
The second argument to reduce is the initial value. If you leave it out, reduce uses the first element as acc and starts at index 1. That shortcut has two costs:
- An empty array with no initial value throws a
TypeError. - The accumulator takes the element's type. That breaks when you want a result of a different type, such as an object built from an array of strings.
console.log([].reduce((acc, n) => acc + n, 0)); // 0
try {
[].reduce((acc, n) => acc + n);
} catch (err) {
console.log(err instanceof TypeError); // true
}Building Pipelines by Chaining Methods
map and filter return arrays, so you can call another array method directly on their result. reduce usually ends the chain because it returns a single value.
const orders = [
{ id: 1, total: 50, status: 'paid' },
{ id: 2, total: 20, status: 'pending' },
{ id: 3, total: 80, status: 'paid' }
];
const paidRevenue = orders
.filter(order => order.status === 'paid')
.map(order => order.total)
.reduce((sum, total) => sum + total, 0);
console.log(paidRevenue); // 130Put filter before map so that map skips elements you are going to discard anyway. The initial value 0 also keeps the pipeline safe when no orders are paid.
Exercise
What does [].reduce((a, b) => Math.max(a, b)) do, and how would you make it return -Infinity for an empty array?
Show answer
It throws a TypeError because the array is empty and there is no initial value. Pass -Infinity as the initial value: [].reduce((a, b) => Math.max(a, b), -Infinity).
Exercise
Using a chain, compute the sum of the squares of the odd numbers in [1, 2, 3, 4, 5].
Show answer
[1, 2, 3, 4, 5].filter(n => n % 2 !== 0).map(n => n * n).reduce((s, n) => s + n, 0) returns 35 (1 + 9 + 25).