Master .reduce() to condense array streams down to a single total sum, object dictionary, or grouped result.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
The .reduce() method executes a user-supplied "reducer" callback function on each element of the array, passing in the return value from the calculation on the preceding element.
.reduce() is the swiss army knife of array methods. It can compute total sums, flatten nested arrays, or build complex objects from array streams in a single pass.
Pass a callback function taking (accumulator, currentValue) and an explicit initial accumulator starting value:
const cartPrices = [15, 25, 10];
// Sum total prices with initial accumulator 0
const totalCost = cartPrices.reduce((sum, price) => {
return sum + price;
}, 0);
console.log(totalCost); // 50
You can use .reduce() with an empty object {} initial value to count occurrences or group items:
const votes = ["yes", "no", "yes", "yes", "no"];
const tally = votes.reduce((acc, vote) => {
acc[vote] = (acc[vote] || 0) + 1;
return acc; // Must return the updated accumulator!
}, {});
console.log(tally); // { yes: 3, no: 2 }
.reduce(), array element 0 becomes the initial accumulator and iteration starts at index 1. On empty arrays, omitting the initial value throws an uncaught TypeError: Reduce of empty array with no initial value!Always supply an initial accumulator value to .reduce(). Next, let's explore clean variable unpacking with Destructuring!