How to use the reduce() method
reduce() runs a function against each element of an array and accumulates the result into a single value. That value can be a number, string, object, or another array.
Syntax
const result = array.reduce((accumulator, currentValue, index, array) => {
return /* updated accumulator */;
}, initialValue);
accumulator: the running result. On the first call, it is set toinitialValue.currentValue: the current element.index: the current index (optional).initialValue: the starting value. Always provide this. Omitting it causes bugs with empty arrays.
I. Sum numbers
Adding all values in an array is the classic reduce() example:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15
Here is how it progresses:
| Iteration | accumulator | currentValue | return value |
|---|---|---|---|
| 1st | 0 | 1 | 1 |
| 2nd | 1 | 2 | 3 |
| 3rd | 3 | 3 | 6 |
| 4th | 6 | 4 | 10 |
| 5th | 10 | 5 | 15 |
II. Flatten an array
You can use reduce() to flatten an array of arrays into a single array:
const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flat = data.reduce((total, value) => [...total, ...value], []);
console.log(flat); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
In modern JavaScript, array.flat() does this more directly. Use flat() when that is all you need.
III. Remove duplicate items
const data = [1, 2, 3, 1, 4, 3, 3, 5];
const unique = data.reduce((accumulator, value) => {
if (accumulator.indexOf(value) === -1) {
accumulator.push(value);
}
return accumulator;
}, []);
console.log(unique); // [1, 2, 3, 4, 5]
In modern JavaScript, you can do the same thing more concisely with Set. See the Set page
for that pattern.
IV. Group items into an object
reduce() is well suited to counting or grouping. Here we count how many times each dish appears in an order:
const orders = ['chicken', 'pizza', 'burger', 'pizza', 'pizza', 'chicken', 'burger', 'pasta'];
const dishCounts = orders.reduce((total, dish) => {
total[dish] = (total[dish] || 0) + 1;
return total;
}, {});
console.log(dishCounts);
// { chicken: 2, pizza: 3, burger: 2, pasta: 1 }
When to use reduce()
reduce() is the right tool when you need to collapse an array into a different shape: a sum, an object, a flattened array. If you find your reduce() getting complex, ask yourself whether a combination of filter()
and map()
would be easier to read.
Common mistakes
Forgetting the initial value. If you skip initialValue and the array is empty, reduce() throws a TypeError. If the array has one element, it returns that element without calling the callback at all, which can surprise you.
// Always provide an initialValue
const sum = [].reduce((total, n) => total + n, 0); // 0
const sumBroken = [].reduce((total, n) => total + n); // TypeError
Writing overly complex reducer logic. If your reducer is hard to follow, split the work into smaller steps with intermediate variables, or use separate filter() and map() calls.