Sub topic 10
Combining Elements into One Value with reduce
This chapter assumes you know arrow functions and the (element, index, array) callback signature that map and filter use. It also assumes you can read and write object properties. reduce uses that same callback pattern but adds one value that carries over from step to step. Most of the confusion about reduce comes from that carried-over value.
The Working Model
reduce walks through an array from left to right and keeps one running value, called the accumulator. For each element it calls your callback with the current accumulator and the element. Whatever the callback returns becomes the accumulator for the next element. When the array runs out, reduce returns the last accumulator.
const prices = [3, 5, 2];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 10The second argument, 0, is the initial value. It is the accumulator the callback receives on the first call.
| Call | accumulator (`sum`) | element (`price`) | returned value |
|---|---|---|---|
| 1 | 0 | 3 | 3 |
| 2 | 3 | 5 | 8 |
| 3 | 8 | 2 | 10 |
The Full Callback Signature
The callback receives four arguments: (accumulator, element, index, array). Most code uses only the first two. The other two are there when you need them.
const result = [10, 20, 30].reduce((acc, value, index, array) => {
console.log(acc, value, index, array.length);
return acc + value;
}, 0);
// 0 10 0 3
// 10 20 1 3
// 30 30 2 3
console.log(result); // 60reduce does not mutate the array. It only reads from it. Your callback can still mutate the array through the fourth argument, but that makes the code hard to follow, so don't do it.
With and Without an Initial Value
The initial value is optional, and leaving it out changes how reduce runs:
- With an initial value, the first call gets the initial value as
accand element 0 asvalue. The callback runs once per element. - Without one, element 0 becomes the starting accumulator and the first call starts at index 1. The callback runs one time fewer than the array has elements.
[10, 20, 30].reduce((acc, value, index) => {
console.log(acc, value, index);
return acc + value;
});
// 10 20 1
// 30 30 2For a plain sum of numbers both forms give the same answer. They stop matching once the accumulator and the elements have different types. Suppose you sum a property of some objects:
const orders = [{ total: 40 }, { total: 15 }];
console.log(orders.reduce((sum, o) => sum + o.total)); // '[object Object]15'
console.log(orders.reduce((sum, o) => sum + o.total, 0)); // 55In the first call, the first order object was the starting accumulator. { total: 40 } + 15 converts the object to a string, and the result is wrong without any error being thrown.
Accumulating Into Objects and Arrays
The accumulator can be any value, not just a number. Starting from {} lets you build lookups and tallies:
const votes = ['yes', 'no', 'yes', 'yes', 'no'];
const tally = votes.reduce((counts, vote) => {
counts[vote] = (counts[vote] ?? 0) + 1;
return counts;
}, {});
console.log(tally); // { yes: 3, no: 2 }Grouping works the same way. Each key holds an array:
const people = [
{ name: 'Ana', city: 'Lisbon' },
{ name: 'Ben', city: 'Oslo' },
{ name: 'Cleo', city: 'Lisbon' }
];
const byCity = people.reduce((groups, person) => {
(groups[person.city] ??= []).push(person.name);
return groups;
}, {});
console.log(byCity); // { Lisbon: ['Ana', 'Cleo'], Oslo: ['Ben'] }Here the callback mutates the accumulator object directly. That is safe because you created the object yourself as the initial value, and no other code holds a reference to it.
You can also turn an array into a keyed index for fast lookup by id:
const users = [{ id: 7, name: 'Ana' }, { id: 9, name: 'Ben' }];
const usersById = users.reduce((index, user) => {
index[user.id] = user;
return index;
}, {});
console.log(usersById[9].name); // 'Ben'Common Errors
Forgetting to return the accumulator
An arrow function with a block body { ... } returns undefined unless you write return. The next call then gets undefined as its accumulator.
try {
['yes', 'no'].reduce((counts, vote) => {
counts[vote] = (counts[vote] ?? 0) + 1;
// missing: return counts;
}, {});
} catch (err) {
console.log(err instanceof TypeError); // true
}The first call works. The second call tries to read undefined['no'] and throws. If the result is undefined, or you get a "Cannot read properties of undefined" error inside a reducer, check the return statement first.
Copying the accumulator on every step
A common "immutable" style rebuilds the accumulator with spread syntax on every call:
const words = ['a', 'b', 'c'];
const slow = words.reduce((acc, w) => ({ ...acc, [w]: true }), {});
console.log(slow); // { a: true, b: true, c: true }The result is correct, but every call copies all the keys collected so far, so the total work grows quadratically. On tens of thousands of elements the slowdown is easy to notice. Because the accumulator is a fresh object that only reduce can see, mutating it and returning it is both safe and linear.
Reaching for reduce when something simpler exists
reduce can express almost any array operation, and that is a reason to be careful with it. A reducer that rebuilds map or filter is harder to read than the method it imitates. Prefer the specific tool when there is one:
| Goal | Clearer choice |
|---|---|
| Transform each element | `map` |
| Keep some elements | `filter` |
| Find one element | `find` |
| Largest of a small number list | `Math.max(...nums)` |
| Group objects by a key (ES2024+) | `Object.groupBy(items, fn)` |
Use reduce when the output is a single value whose shape differs from the input: a total, a tally, an index, or a merged object. One note on Math.max(...nums): spreading passes every element as a separate argument, so very large arrays can exceed the engine's argument limit. For those arrays, nums.reduce((max, n) => (n > max ? n : max), -Infinity) has no such limit.
reduceRight
reduceRight works like reduce but walks from the last element to the first. It matters when order affects the result, as with string building or applying functions in sequence:
console.log(['a', 'b', 'c'].reduceRight((acc, s) => acc + s, '')); // 'cba'
const compose = (...fns) => x => fns.reduceRight((value, fn) => fn(value), x);
const addOne = n => n + 1;
const double = n => n * 2;
console.log(compose(addOne, double)(5)); // 11 (double first, then addOne)Exercise
What does this print, and why? console.log([{ n: 2 }, { n: 3 }, { n: 4 }].reduce((acc, item) => acc + item.n)); Fix it so it prints 9.
Show answer
It prints '[object Object]34'. With no initial value, the first object becomes the accumulator. { n: 2 } + 3 converts the object to the string '[object Object]' and appends 3, then 4 is appended to that string. Passing 0 as the initial value fixes it: .reduce((acc, item) => acc + item.n, 0) returns 9.
Exercise
Write a reduce call that turns ['apple', 'avocado', 'banana', 'blueberry', 'cherry'] into an object mapping each first letter to the number of words that start with it.
Show answer
const counts = words.reduce((acc, w) => { const k = w[0]; acc[k] = (acc[k] ?? 0) + 1; return acc; }, {}); produces { a: 2, b: 2, c: 1 }. The {} initial value sets the accumulator's type, ?? 0 handles the first time a key appears, and return acc passes the object on to the next call.