codeburst

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

Follow publication

Learn & Understand JavaScript’s Reduce Function

Brandon Morelli
codeburst
Published in
4 min readNov 14, 2017

--

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

Reduce Definition & Syntax

let result = arr.reduce(callback);// Optionally, you can specify an initial valuelet result = arr.reduce(callback, initValue);

Reduce vs. For Loop

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

Specifying an Initial Value

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

Reduce & ES6

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

Challenge

let data = [
{
country: 'China',
pop: 1409517397,
},
{
country: 'India',
pop: 1339180127,
},
{
country: 'USA',
pop: 324459463,
},
{
country: 'Indonesia',
pop: 263991379,
}
]
let sum = data.reduce((acc, val) => {
return val.country == 'China' ? acc : acc + val.pop;
}, 0);

Closing Notes:

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

--

--

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)