Sub topic 6
reduce: Folding an Array into One Value
This chapter assumes you know how callbacks work in array methods and have used map and filter. map and filter both return arrays. reduce can return anything: a number, a string, an object, or another array. It does this by carrying one value, the accumulator, through the whole array and updating it at each step.
The Working Model
reduce takes two arguments:
- A reducer callback with the signature
(accumulator, currentValue, index, array). - An optional initial value for the accumulator.
For each element, reduce calls the reducer with the current accumulator and the element. Whatever the reducer returns becomes the accumulator for the next call. After the last element, reduce returns the final accumulator.
const total = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0);
console.log(total); // 10The equivalent loop makes the mechanics visible:
const numbers = [1, 2, 3, 4];
let acc = 0;
for (const n of numbers) {
acc = acc + n;
}
console.log(acc); // 10The reducer is the loop body, and the initial value is the starting assignment. reduce hides the let and the reassignment.
Tracing the Accumulator
Step through the sum call by call:
| Call | acc (in) | n | Returned (acc out) |
|---|---|---|---|
| 1 | 0 | 1 | 1 |
| 2 | 1 | 2 | 3 |
| 3 | 3 | 3 | 6 |
| 4 | 6 | 4 | 10 |
When a reduce call confuses you, trace it like this table. Write down the accumulator going in and the value coming out for each element.
The Accumulator Does Not Have to Be a Number
The accumulator's type is set by the initial value and by what the reducer returns. Here is a reducer that finds the maximum:
const scores = [42, 97, 63, 85];
const highest = scores.reduce((max, s) => (s > max ? s : max), -Infinity);
console.log(highest); // 97And here the accumulator is a string:
const tags = ['js', 'arrays', 'reduce'];
const hashtags = tags.reduce((text, tag, i) => text + (i > 0 ? ' ' : '') + '#' + tag, '');
console.log(hashtags); // '#js #arrays #reduce'The second example uses the index argument to avoid a leading space. The fourth argument, array, is rarely needed, but it is there if a reducer must look at the whole input.
You can also count with a running total. The accumulator stays a number even though the elements are objects:
const tasks = [
{ title: 'write', done: true },
{ title: 'test', done: false },
{ title: 'ship', done: true }
];
const doneCount = tasks.reduce((count, t) => count + (t.done ? 1 : 0), 0);
console.log(doneCount); // 2The Most Common Error: Forgetting to Return
const broken = [1, 2, 3].reduce((acc, n) => {
acc + n; // no return
}, 0);
console.log(broken); // undefined
const fixed = [1, 2, 3].reduce((acc, n) => {
return acc + n;
}, 0);
console.log(fixed); // 6A related mistake is using the wrong type of initial value, for example starting a sum at '', which gives string concatenation ('123'). Make the initial value the same type you expect back. The next chapter covers what happens when you leave the initial value out and the array is empty.
Exercise
What does [2, 3, 4].reduce((acc, n) => acc * n, 0) return, and what initial value makes it compute the product correctly?
Show answer
It returns 0, because 0 multiplied by anything stays 0. Use 1, the identity value for multiplication: [2, 3, 4].reduce((acc, n) => acc * n, 1) returns 24.
Exercise
Write a reduce call that returns the length of the longest string in ['map', 'filter', 'reduce', 'flatMap'].
Show answer
['map', 'filter', 'reduce', 'flatMap'].reduce((longest, s) => Math.max(longest, s.length), 0) returns 7. The accumulator is a number that starts at 0, and each step keeps the larger of the current best and the current string's length.