JavaScript Array.reduce() Method - Accumulate Values
Deep dive into Array.reduce() for summing, grouping, flattening, and building complex data structures. Includes real-world examples and best practices. Free reference.
Detailed Explanation
Understanding Array.reduce()
Array.reduce() executes a reducer function on each element of the array, passing the return value from the previous iteration as an accumulator. The final result is a single accumulated value — which can be a number, string, object, array, or any other type.
Syntax
const result = array.reduce((accumulator, currentValue, index, array) => {
// return updated accumulator
}, initialValue);
Always provide an initialValue. Without it, reduce uses the first element as the initial accumulator, which throws on empty arrays and causes confusing type errors.
Common Patterns
Sum numbers:
const total = [1, 2, 3, 4, 5].reduce((sum, n) => sum + n, 0);
// total: 15
Group by property:
const people = [
{ name: "Alice", dept: "Eng" },
{ name: "Bob", dept: "Sales" },
{ name: "Carol", dept: "Eng" }
];
const byDept = people.reduce((acc, person) => {
const key = person.dept;
acc[key] = acc[key] || [];
acc[key].push(person);
return acc;
}, {});
// byDept: { Eng: [{Alice}, {Carol}], Sales: [{Bob}] }
Flatten nested arrays (before flat existed):
const nested = [[1, 2], [3, 4], [5]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);
// flat: [1, 2, 3, 4, 5]
Count occurrences:
const fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const counts = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
// counts: { apple: 3, banana: 2, cherry: 1 }
When NOT to Use reduce
If a simpler method exists, use it:
- Summing? Consider a plain
forloop for clarity - Filtering + mapping? Chain
.filter().map()instead - Grouping? Use
Object.groupBy()(ES2024) when available
reduce is powerful but can be hard to read when overused.
Use Case
Use reduce() for calculating totals (shopping cart sums, statistics), grouping data by category, building lookup objects from arrays, counting occurrences, composing function pipelines, and any other accumulation pattern that does not fit map or filter.