reduce()
ES5+Executes a reducer function on each element of the array, resulting in a single output value.
Syntax
array.reduce(callback(accumulator, currentValue, index, array), initialValue)Parameters
callback Function A function to execute on each element
initialValue any optionalInitial value for the accumulator
Return Value
The single value that results from the reduction
Examples
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, cur) => acc + cur, 0);
console.log(sum); 📌 When to Use
Use reduce() when you need to transform an array into a single value or a different data structure. It's the most versatile array method - perfect for summing, grouping, flattening, or building objects from arrays.
⚠️ Common Mistakes
Forgetting to provide an initial value - causes errors on empty arrays and unexpected behavior
Not returning the accumulator in every code path of the callback
Using reduce() for simple operations where map() or filter() would be clearer
✅ Best Practices
Always provide an initial value to avoid bugs with empty arrays
For complex reductions, break the logic into a named function for readability
Use reduce() to replace multiple map/filter chains for better performance
⚡ Performance Notes
reduce() is highly efficient for single-pass operations. It can replace chained map().filter().map() calls with a single iteration, reducing memory allocations. However, for simple sums or concatenations, a traditional for loop may be marginally faster.
🌍 Real World Example
Grouping Data by Category
Group an array of transactions by their category for a financial dashboard
const transactions = [
{id: 1, category: 'food', amount: 50},
{id: 2, category: 'transport', amount: 30},
{id: 3, category: 'food', amount: 25}
];
const byCategory = transactions.reduce((groups, tx) => {
const key = tx.category;
groups[key] = groups[key] || [];
groups[key].push(tx);
return groups;
}, {});
// Result: {food: [{...}, {...}], transport: [{...}]}