Check out our Angular Book Series.

Understanding The JavaScript Reducer Function

Despite how long I've been creating JavaScript applications, I keep learning new things and discovering new little pieces of the language that I didn't know existed. Today I found the reducer function.

The reducer will loop over an array, with the intent of reducing the full array into a single value. The most common use case of this is to add up all the numbers in an array, like this:

console.log([1, 2, 3, 4].reduce((accumulator, currentValue) =>
accumulator + currentValue));

The reducer function accepts two arguments, the first is the accumulator and the second is the currentValue.

The first time the reduce function runs, it passes in the first two values from the array. The accumulator is the first value, 1 in this case. The currentValue is the second value,. the 2.

The second time the function is executed it returns the results of the first function run into the accumulator, and the third function. In this case, 3 is the results of the first run, and 3 is the third element in the array.

The third time the reducer is called it gets 6--the results of the third run of the function--and 4--the fourth item in the array. Then it has no more items to execute and returns the results.

Adding numbers in an array is a simple use case for this, but this could be used in much more advanced situations too, such as looping over an array of objects. Imagine you are creating a log display and want to show all the users who have edited something. Just use reducer to get the users list on each log item. Or maybe you're dealing with rights limited content and want to figure out what country the content is in; this could help if you loop over an array of 'rights metadata' objects.

Play with the code here.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version