The JavaScript Array reduce() Method: Complete Guide
Direct Answer & Key Concept
The Array.prototype.reduce() method executes a user-supplied reducer callback function on each element of the array in order, passing in the return value from the calculation on the preceding element, culminating in a single output value.
// Grouping and Summing with reduce()
const transactions = [
{ type: "deposit", amount: 100 },
{ type: "withdrawal", amount: 40 },
{ type: "deposit", amount: 250 }
];
const balanceSummary = transactions.reduce(
(acc, txn) => {
if (txn.type === "deposit") acc.totalDeposits += txn.amount;
else acc.totalWithdrawals += txn.amount;
acc.netBalance = acc.totalDeposits - acc.totalWithdrawals;
return acc;
},
{ totalDeposits: 0, totalWithdrawals: 0, netBalance: 0 }
);
console.log(balanceSummary);
// { totalDeposits: 350, totalWithdrawals: 40, netBalance: 310 }What is Array.prototype.reduce()?
The reduce() method is one of JavaScript's most powerful functional array utilities. It iterates across an array and executes an accumulator callback on each element, compressing the entire array into a single accumulated value—such as a number, string, array, or dictionary object.
Syntax and Anatomy of reduce()
array.reduce((accumulator, currentValue, currentIndex, array) => {
return updatedAccumulator;
}, initialValue);
accumulator: The accumulated value returned from the previous iteration callback (orinitialValueon the first pass).currentValue: The current array element being processed.initialValue: Crucial parameter. The starting value of the accumulator. If omitted,reduce()defaults to using the first element of the array, which can cause runtime crashes on empty arrays.
3 Practical Real-World reduce() Patterns
1. Summing Array Totals
const expenses = [45, 12, 89, 24];
const totalCost = expenses.reduce((acc, curr) => acc + curr, 0);
console.log(totalCost); // 170
2. Grouping Objects by Property (Categorization)
const inventory = [
{ name: "Apple", category: "Fruit" },
{ name: "Carrot", category: "Vegetable" },
{ name: "Banana", category: "Fruit" }
];
const grouped = inventory.reduce((acc, item) => {
acc[item.category] = acc[item.category] || [];
acc[item.category].push(item.name);
return acc;
}, {});
console.log(grouped);
// { Fruit: ["Apple", "Banana"], Vegetable: ["Carrot"] }
3. Counting Frequency of Items
const votes = ["yes", "no", "yes", "yes", "no"];
const tally = votes.reduce((acc, vote) => {
acc[vote] = (acc[vote] || 0) + 1;
return acc;
}, {});
console.log(tally); // { yes: 3, no: 2 }
Common Mistakes with reduce()
- Omitting the initialValue on empty arrays: Calling
[].reduce((a, b) => a + b)throws a fatalTypeError: Reduce of empty array with no initial value. Always provide an initial value. - Forgetting to return the accumulator: If you omit
return accinside your callback, the accumulator becomesundefinedon the next iteration pass.