JavaScript’s Reduce Function

Dev Singh. October 21, 2018 Comments

How to use Array.prototype.reduce()

Example of other similar array functions.

Reduce Definition & Syntax

The reduce() method is used to apply a function to each element in the array to reduce the array to a single value.

Here’s what the syntax looks like:

let result = arr.reduce(callback);
// Optionally, you can specify an initial value
let result = arr.reduce(callback, initValue);
  • result — the single value that is returned.
  • arr — the array to run the reduce function on.
  • callback — the function to execute on each element in the array.
  • initValue — an optionally supplied initial value. If this value is not supplied, the 0th element is used as the initial value.

Our callback function can take four arguments. You will recognize three of the arguments from the map() and filter() methods. The new argument is the accumulator.

  • accumulator — the accumulator accumulates all of the callbacks returned values.
  • val — the current value being processed
  • index — the current index of the value being processed
  • arr — the original array

Reduce vs. For Loop

You can think of reduce() as a for loop, that is specifically for using the values of an array to create something new. Consider the following code:

var arr = [1, 2, 3, 4];
var sum = 0;
for(var i = 0; i < arr.length; i++) {
    sum += arr[i];
}
// sum = 10

The goal of the above code is to find the sum of all of the values in our array. It loops through our array and adds each value to a variable one at a time. When it’s done, our sum is equal to 10. While this code works, there is a much easier way to achieve the same result — using the reduce() function.

To use the reduce() function, we’ll start with the same simple array of numbers:

let arr = [1,2,3,4];

arr is the array we’re going to reduce. We want to find the sum of all the values in our array. To do this, each iteration we will add the current value to our accumulator and return it. This returned value will then be our new accumulator.

let sum = arr.reduce((acc, val) => {
  return acc + val;
});

Awesome. We’ve used the variable acc to represent our accumulator. As our reduce function works through the arr array, the acc value will increase until the function has completed.

Once complete, we can log out our sum variable and see that the function worked:

sum = 10

Super!

Specifying an Initial Value

Remember above when I specified that we can use an optional initial value? It’s pretty easy to set that up. We’ll use the same example as above. We’re going to sum our array, but this time, we want to start with an initial value of 100.

let sum = arr.reduce((acc, val) => {
  return acc + val;
}, 100);

As you can see, the code above is almost identical to the previous example. All that’s changed is we’ve added a second argument after our callback. I’ve passed in the number 100 as our starting point. Now, when we run the function, sum will equal 110.

Reduce & ES6

Working with arrow functions allows us to simplify our code even more. When you return from an arrow function you can omit the brackets and the return keyword to specify that you are returning a value.

The code above is the exact same as this code:

let sum = arr.reduce((acc, val) => acc + val, 100);

Pretty cool huh? With just one line of code we can take the number 100 and add it to the sum of an entire array! We’ve come a long way since our forloop!

Challenge

Consider the following data:

let data = [
  {
    country: 'China',
    pop: 1409517397,
  },
  {
    country: 'India',
    pop: 1339180127,
  },
  {
    country: 'USA',
    pop: 324459463,
  },
  {
    country: 'Indonesia',
    pop: 263991379,
  }
]

Using the reduce() method, how would you sum up the population of every country except China?

Consider your answer, then scroll down for the solution…

***

*****

*******

*****

***

Here’s how I did it:

let sum = data.reduce((acc, val) => {
  return val.country == 'China' ? acc : acc + val.pop;
}, 0);

I’m using an initial value of 0 to start off. From there, I check to see if the the country name of the current element matches 'China', if it does, I simply return the accumulator unchanged — this essentially skips China. If the country is anything other than China, I return the accumulator plus the population of the current country.

After running the function we get sum = 1927630969.

  • JavaScript
  • Functional Programming
  • reduce-js