Learn & Understand JavaScript’s Reduce Function

综合技术 JavaScript Live (源链)

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


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!


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! ⬇⬇


全栈与大前端,前端工程师进阶该如何抉择?... 今天,我想跟大家谈谈前端工程师进阶方向的问题。关于这个问题市场上的杂音太多,各种误解、误导太多,我想谈谈我的观察和理解,包括全栈、Node全栈、大前端等,希望对大家有所帮助。 不想成为全栈的前端不是好程序员。 数年以前,全栈工程师的理念忽然风靡墙内外,成为开发者们津津乐道的话题。数...
Changing getElementById to get pause code GetEleme... So I've got this working code Hello Worldsummarylost anothergood night moonfind meExpand All +var elems = document.getElementsByTagName("details...
Calling a function when a & lt; Div &... I'm working on a web page that is supposed to have a block of text that changes from "Click Me" to "Ouch!" when the user clicks anywhere inside the...
理解JavaScript中的作用域 什么是变量,什么是作用域? 变量: 简单来说就是在特定时间内保存特定值的一个名字而已,由于不存在定义某个变量必须要保存某种数据类型值的规则,所以变量的值及其数据类型可以在脚本生命周期内任意改变,变量可能包含两种不同的数据类型得值:基本类型值和引用类型值。基本数据类型包括:Un...
原型继承(翻译 vjeux 文章) 在网页上我们随处可见说javascript是一种原型继承。然而javascript仅仅默认地在使用new操作符的这种特殊情况下提供了原型继承。因此,许多js的解读都让人感到很迷惑。 这篇文章用于阐述什么是原型继承以及如何在js中使用原型继承。 原型继承的目的:在 js 中实现一种对象之间的资源(...
JavaScript Live责编内容来自:JavaScript Live (源链) | 更多关于

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

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

使用声明 | 英豪名录