codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Learn & Understand JavaScript’s Reduce Function

Learn how to use Array.prototype.reduce()

Brandon Morelli
codeburst
Published in
4 min readNov 14, 2017

--

Udemy Black Friday Sale — Thousands of Web Development & Software Development courses are on sale for only $10 for a limited time! Full details and course recommendations can be found here.

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

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 valuelet 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

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 👏button below a fewtimes to show your support! ⬇⬇

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Responses (25)

Write a response