Sub topic 6
reduce: Folding an Array into One Value
map gives you one output element for each input element. filter gives you some of the input elements. reduce has no fixed output shape. It walks the array once, carries a running value from step to step, and returns whatever that value is at the end. That value can be a number, a string, an object, a Map, or another array.
This chapter assumes you are comfortable with arrow functions, with callbacks passed to array methods, and with the element/index/array arguments covered earlier. Choosing the initial value and handling empty arrays get their own chapter next. Here the focus is how reduce works: what the callback receives, what it must return, and how one call becomes the next.
The Shape of a reduce Call
reduce takes two arguments. The first is a reducer callback. The second, which is optional, is the initial value of the accumulator.
const total = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0);
console.log(total); // 10The reducer receives up to four arguments:
| Parameter | Common name | Meaning |
|---|---|---|
| 1st | `acc` / `accumulator` | The value returned by the previous call, or the initial value on the first call |
| 2nd | `current` / `n` / `item` | The element being processed |
| 3rd | `index` | The index of that element |
| 4th | `array` | The array `reduce` was called on |
Compared with map and filter, the reducer has one extra argument at the front, the accumulator. Whatever the reducer returns becomes acc for the next element. After the last element, reduce returns that final value.
Tracing the Fold Step by Step
The name "fold" describes what happens: the array is folded into the accumulator one element at a time. Here is the sum above, traced call by call:
| Call | `acc` in | `n` | `index` | Returned (`acc` out) |
|---|---|---|---|---|
| 1 | 0 | 1 | 0 | 1 |
| 2 | 1 | 2 | 1 | 3 |
| 3 | 3 | 3 | 2 | 6 |
| 4 | 6 | 4 | 3 | 10 |
The result is 10, the acc out of the final call.
You can watch the same trace by logging inside the reducer:
const result = [1, 2, 3, 4].reduce((acc, n, index) => {
const next = acc + n;
console.log(`index ${index}: ${acc} + ${n} -> ${next}`);
return next;
}, 0);
console.log(result);
// index 0: 0 + 1 -> 1
// index 1: 1 + 2 -> 3
// index 2: 3 + 3 -> 6
// index 3: 6 + 4 -> 10
// 10How reduce Works Internally
A simplified version of reduce written as a plain function makes the rules concrete. It follows the specification's behavior on the points that matter in practice.
function myReduce(array, reducer, ...rest) {
const length = array.length; // length is read once, at the start
let i = 0;
let acc;
if (rest.length > 0) {
acc = rest[0]; // an initial value was supplied
} else {
while (i < length && !(i in array)) i++; // skip leading holes
if (i >= length) {
throw new TypeError('Reduce of empty array with no initial value');
}
acc = array[i]; // first present element becomes acc
i++;
}
for (; i < length; i++) {
if (i in array) { // holes in sparse arrays are skipped
acc = reducer(acc, array[i], i, array);
}
}
return acc;
}
console.log(myReduce([1, 2, 3, 4], (acc, n) => acc + n, 0)); // 10
console.log(myReduce([1, 2, 3, 4], (acc, n) => acc + n)); // 10
console.log([1, 2, 3, 4].reduce((acc, n) => acc + n)); // 10Several behaviors follow from this code:
- With no initial value, the first element becomes the accumulator and the reducer starts at index 1. A four-element array then produces three reducer calls, not four.
- The check for an initial value counts arguments, not values. Passing
undefinedexplicitly still counts as supplying one, so[1, 2].reduce((a, n) => a + n, undefined)givesNaN. - Holes in sparse arrays are skipped.
[1, , 3].reduce((a, n) => a + n, 0)returns4, and the reducer runs only twice. - The length is read once. Elements you push onto the array during the reduce are not visited.
The Accumulator Can Be Any Type
The sum example hides how general reduce is. The accumulator only has to be something the reducer knows how to combine with the next element.
A single number: maximum
const scores = [72, 95, 61, 88];
const highest = scores.reduce((max, s) => (s > max ? s : max), -Infinity);
console.log(highest); // 95A string
const tags = ['js', 'arrays', 'reduce'];
const hashtags = tags.reduce(
(text, tag, index) => text + (index > 0 ? ' ' : '') + '#' + tag,
''
);
console.log(hashtags); // '#js #arrays #reduce'An object with several running totals
A single pass can track more than one quantity:
const temps = [18, 22, 15, 25, 20];
const stats = temps.reduce(
(acc, t) => ({
min: Math.min(acc.min, t),
max: Math.max(acc.max, t),
sum: acc.sum + t,
count: acc.count + 1
}),
{ min: Infinity, max: -Infinity, sum: 0, count: 0 }
);
console.log(stats); // { min: 15, max: 25, sum: 100, count: 5 }
console.log(stats.sum / stats.count); // 20Another array
reduce can rebuild map and filter, which shows they are special cases of a fold:
const mapWithReduce = (arr, fn) =>
arr.reduce((out, x, i) => {
out.push(fn(x, i));
return out;
}, []);
const filterWithReduce = (arr, pred) =>
arr.reduce((out, x, i) => {
if (pred(x, i)) out.push(x);
return out;
}, []);
console.log(mapWithReduce([1, 2, 3], n => n * 10)); // [10, 20, 30]
console.log(filterWithReduce([1, 2, 3, 4], n => n % 2 === 0)); // [2, 4]That doesn't mean you should write them this way. When map or filter fits, use it, because the method name tells the reader what the code does. Reach for reduce when the output's shape differs from the input's. Grouping, counting, and indexing patterns build on this idea in a later chapter.
Common Errors
Forgetting to return the accumulator
A braced arrow function body needs an explicit return. Without one, the reducer returns undefined, and that becomes the next acc.
const broken = [1, 2, 3].reduce((acc, n) => {
acc + n; // computed, then thrown away
}, 0);
console.log(broken); // undefined
const fixed = [1, 2, 3].reduce((acc, n) => {
return acc + n;
}, 0);
console.log(fixed); // 6The symptom is usually a TypeError on the second call, such as "Cannot read properties of undefined", rather than a wrong final value.
Returning the result of push
Array.prototype.push returns the new length, not the array. Returning it turns the accumulator into a number:
try {
[1, 2, 3].reduce((acc, n) => acc.push(n * 2), []);
} catch (err) {
console.log(err instanceof TypeError); // true: acc.push is not a function
}
const doubled = [1, 2, 3].reduce((acc, n) => {
acc.push(n * 2);
return acc;
}, []);
console.log(doubled); // [2, 4, 6]Mixing up parameter order
The accumulator comes first and the element second. Writing (n, acc) => ... runs without errors and gives nonsense, because the names don't match the values. Keep the conventional order and names.
Copying the accumulator on every step
Code that returns a fresh copy on every call looks tidy:
const ids = Array.from({ length: 5 }, (_, i) => i);
const slow = ids.reduce((acc, id) => [...acc, id * 2], []);
const fast = ids.reduce((acc, id) => {
acc.push(id * 2);
return acc;
}, []);
console.log(slow); // [0, 2, 4, 6, 8]
console.log(fast); // [0, 2, 4, 6, 8]The spread version copies the whole accumulator on each step, so its total work grows with the square of the array length. At tens of thousands of elements the slowdown is noticeable. Mutating the accumulator is safe here because your own initial value created it and no other code holds a reference to it. That differs from mutating the input elements, which the immutability chapter warns against.
Using reduce where a simpler method exists
Checking whether any element matches, or finding the first match, with reduce visits every element even after the answer is known. some, every, and find stop early and say what they do. They are covered later in the tutorial.
Reading a Reducer
When you meet an unfamiliar reduce, answer these questions in order:
- What is the initial value? That tells you the result's type.
- What does one call return? It must have the same type as the initial value.
- How does each element change the accumulator?
If you can't answer the first two quickly, consider rewriting the reduce as a named function or a for...of loop.
Exercise
How many times does the reducer run in [5, 10, 15].reduce((a, n) => a + n), and what are a and n on the first call?
Show answer
It runs twice. With no initial value, the first element (5) becomes the accumulator, so the first call receives a = 5 and n = 10 (index 1) and returns 15. The second call receives a = 15 and n = 15 and returns 30.
Exercise
This code throws "Cannot read properties of undefined (reading 'count')". Why, and how do you fix it? const r = ['a', 'b'].reduce((acc, ch) => { acc.count += 1; }, { count: 0 });
Show answer
The braced arrow body has no return statement, so the first call returns undefined and the second call tries to read undefined.count. Add return acc; after acc.count += 1;, or write it as an expression: (acc, ch) => ({ count: acc.count + 1 }).
Exercise
Use one reduce call to turn [3, -1, 4, -5, 9] into { positives: 16, negatives: -6 }.
Show answer
[3, -1, 4, -5, 9].reduce((acc, n) => { if (n >= 0) acc.positives += n; else acc.negatives += n; return acc; }, { positives: 0, negatives: 0 }). The initial object fixes the result's shape, and each call adds the element to one of the two totals and returns the same object.
Exercise
What does [1, , 3, , 5].reduce((acc, n, i) => acc + i, 0) return, and why?
Show answer
It returns 6. Holes are skipped, so the reducer runs only for indexes 0, 2, and 4, and 0 + 2 + 4 = 6.