Learn & Understand JavaScript’s Reduce Function

This is article #3 in a four part series this week.

  • Learn Map — Array.prototype.map()
  • Learn FilterArray.prototype.filter()
  • Learn ReduceArray.prototype.reduce()
  • Chaining Map, Filter, and Reduce

I strongly encourage you to read my articles about Map & Filter (linked above) before proceeding

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 used to test each element of the oldArr . Returning true keeps the element, returning false to not keep it.
  • 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

Awesome!

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 for loop!

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 .

Closing Notes:

Thanks for reading! This has been a brief introduction into JavaScript’s reduce() function. If you’re ready to finally learn Web Development, check out the The Ultimate Guide to Learning Full Stack Web Development in 6 months .

I publish 4 articles on web development each week. Please consider entering your email here if you’d like to be added to my once-weekly email list, and follow me on Twitter .

If this post was helpful, please click the clap :clap:button below a fewtimes to show your support! ⬇⬇

稿源:JavaScript Live (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Learn & Understand JavaScript’s Reduce Function

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录