Javascript Reduce function

Reduce

Finally, we come to .reduce(), which, admittedly, is the most confusing of the three methods. The name of the method refers to reducing multiple values to one. However, I found that it’s easier to think of it as building up rather than reducing.

The method works by defining a starting point. As the method iterates over each value, that starting point is modified and passed down.

Here’s a classic case of adding a series of numbers together. Pretend we’re calculating the total donations to your favorite charity:

const donations = [5, 20, 100, 80, 75];
let total = 0;for(let i=0; i < donations.length; i++) {
   total += donations[i];
}

Unlike .map() and .filter(), the .reduce() method’s callback requires two parameters: an accumulator and the current value. The accumulator will be the first parameter and is the “pass it down” value.

const donations = [5, 20, 100, 80, 75];
let total = donations.reduce((total,donation) => {
   return total + donation;
});

We could also pass a second argument to the .reduce() method itself. This would serve as the starting value for the accumulator. Let’s say we’re adding yesterday’s donations that totaled $450.

const donations = [5, 20, 100, 80, 75];
let total = donations.reduce((total,donation) => {
   return total + donation;
}, 450);

Leave a Comment