Topic 49 of 87
Array reduce()
Overview
The .reduce() method is the most powerful (and most confusing) array method. It runs a function on each array element to "reduce" the array down to a single value (like a number, string, or even a brand new object).
It keeps track of an 'accumulator'—a running total that gets updated in every iteration and is ultimately returned at the end.
Syntax
Summing Numbers
javascript
const prices = [10, 20, 30];
// syntax: arr.reduce((accumulator, currentValue) => { ... }, initialValue)
const total = prices.reduce((acc, curr) => {
return acc + curr;
}, 0); // 0 is the starting value of 'acc'
console.log(total); // 60Reducing to an Object
javascript
// Counting occurrences of items
const votes = ["Yes", "No", "Yes", "Yes"];
const tally = votes.reduce((acc, vote) => {
if (!acc[vote]) acc[vote] = 1;
else acc[vote]++;
return acc; // MUST return the accumulator!
}, {}); // Starting value is an empty object
console.log(tally); // { Yes: 3, No: 1 }Common Pitfalls
- Forgetting to provide the
initialValue(the0or{}at the end). If omitted, JS uses the first element of the array as the initial value. This works for simple number arrays, but leads to catastrophic object-object concatenation bugs when dealing with arrays of objects.
Interview Questions
Q:
Can you implement a
.map() function using .reduce()?A:
Yes! By passing an empty array [] as the initial value, you can push transformed items into the accumulator inside the callback, and return the accumulator.
Real-World Example
Calculating the grand total price of a complex shopping cart array in an e-commerce app.
example
javascript
const grandTotal = cart.reduce((total, item) => total + (item.price * item.quantity), 0);Check Your Knowledge
Test your understanding of Array reduce() with these quick questions.