**reduce()** is the most powerful (and complex) array method. It processes each element and **accumulates** a result. The accumulator starts as the **initialValue** (always provide it). Use it for sums, grouping, transforming to objects, and more. map() and filter() can be implemented with reduce().
1Understanding Array.reduce()
reduce() is the most powerful (and complex) array method. It processes each element and accumulates a result. The accumulator starts as the initialValue (always provide it). Use it for sums, grouping, transforming to objects, and more. map() and filter() can be implemented with reduce().
Always provide an initialValue as the second argument. Without it, reduce() uses the first element as the accumulator — which can cause bugs with empty arrays.
// Sum
const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15
// Group by category
const items = [
{ name: 'apple', type: 'fruit' },
{ name: 'banana', type: 'fruit' },
{ name: 'carrot', type: 'veggie' },
];
const grouped = items.reduce((acc, item) => {
(acc[item.type] ||= []).push(item.name);
return acc;
}, {});
console.log(grouped);2Practical Example
Here is a real-world application of Array.reduce() showing how it is used in production JavaScript code.
// Implement map() using reduce()
const doubled = [1,2,3].reduce((acc, n) => {
acc.push(n * 2);
return acc;
}, []);
console.log(doubled); // [2, 4, 6]3Best Practices
Follow these guidelines when working with Array.reduce():
1. Always provide an initialValue
2. Use reduce for complex aggregation (groupBy, pivot)
3. Prefer map/filter for simple cases — they're more readable
Tip: Always provide an initialValue as the second argument. Without it, reduce() uses the first element as the accumulator — which can cause bugs with empty arrays.
// Sum
const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15
// Group by category
const items = [
{ name: 'apple', type: 'fruit' },
{ name: 'banana', type: 'fruit' },
{ name: 'carrot', type: 'veggie' },
];
const grouped = items.reduce((acc, item) => {
(acc[item.type] ||= []).push(item.name);
return acc;
}, {});
console.log(grouped);