logo

Scott A. Price

Front-End Developer

JavaScript Array Methods: reduce()

July 23rd, 2020

The reduce() method is very versatile since it can be used in place of most other array methods. The reduce() method does not mutate the array, but it returns a new value based on the existing array. MDN web docs defines the reduce() method like this:

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

I do not find that definition helpful. Unless you happen to know what a ‘reducer function’ is, or that a ‘single output value’ does not necessarily mean a single value, I think it is rather confusing. In the following paragraphs I will define ‘reducer function’ and what ‘single output value’ really means.

Reducer Function

A reducer function is a function that takes a group of values and performs an operation on them which combines them into a single value. The reducer starts with the first value in the group, performs an operation on it, and stores it in a variable called an accumulator. Next, it performs the same operation on the second value and stores it in the accumulator. It continues doing this for every value in the group until the last value has been processed. The value of the accumulator variable at this point is the single value that is returned.

The reducer function also takes the current value of the accumulator function as an input. So the value of the accumulator after each time the reducer function is executed is a function of the previous value of the accumulator and the current value from the group of values.

Here is a reducer function that will sum the values in an array of numbers:

const reducer = arr => { let accumulator = 0 for( let i = 0; i < arr.length; i++) { accumulator = accumulator + arr[i] } return accumulator } const array = [1, 2, 3, 4, 5, 6] console.log(reducer(array)) // logs 21 to the console

This function initializes an ‘accumulator’ variable with the value 0. Then, it iterates through each value of the array that is passed to the function, which is then added to the accumulator. Finally, it returns the new value to the accumulator variable. The result is the sum of the numbers in the array: 21.

Single Output Value

The ‘single output value’ produced by the reducer function is not necessarily a single value like a number or a string. It can also be another array, a JavaScript object, or some other JavaScript data type.

As an example, I will update our reducer function to produce an array-like object. (To learn more about array-like objects see this article.):

const reducer = arr => { let accumulator = {} for( let i = 0; i < arr.length; i++) { accumulator = { [i]: arr[i], ...accumulator } } accumulator.length = arr.length return accumulator } const array = [1, 2, 3, 4, 5, 6] console.log(reducer(array))

This function will log the following to the console:

Object { 0: 1 1: 2 2: 3 3: 4 4: 5 5: 6 length: 6 __proto__: Object }

Using the reduce() method

The reduce method takes two parameters. The first parameter is the reducer function and the second parameter is the initial value. They are both discussed below:

The reduce() method’s reducer function

The first parameter of the reduce() method is a reducer function. The reducer function itself has two required parameters and two optional parameters. The first required parameter is the accumulator. Much like the accumulator variable in the examples above, the accumulator parameter stores the value returned in each iteration of the callback function. The second required parameter is the current element being processed in the array.

The third parameter of the reducer function, which is optional, is the index of the current element being processed in the array, and the fourth parameter (also optional) is the whole array upon which the reduce() method was called. These parameters are only used if you need access to these values within the body of the reducer function.

The following example uses just the first two parameters of the reducer function to sum the elements of an array:

const array = [1, 2, 3, 4, 5, 6] const sum = array.reduce((acc, cur) => acc + cur) console.log(sum) // logs 21 to the console

The reduce() method’s initial value

The second parameter of the reduce() method is optional. It sets the initial value of the accumulator. If the initial value is omitted, the reduce() method sets the initial value of the accumulator to the first value of the array. In the example above, we did not need to set the initial value since setting the initial value of the accumulator to the first value of the array returned the correct result. We could have set the initial value of the reduce method to zero and produced the same result, like this:

const array = [1, 2, 3, 4, 5, 6] const sum = array.reduce((acc, cur) => acc + cur, 0) console.log(sum) // logs 21 to the console

In other cases, if we do not set the initial value, our answer will be incorrect. In the following example, which produces the same array-like object from the second example in this article, if we did not set the initial value to an empty object, the first value of the array would not be included in the object:

const array = [1, 2, 3, 4, 5, 6] const arrayLikeObject = array.reduce((acc, cur, i, arr) => { return { [i]: cur, length: arr.length, ...acc } }, {}) console.log(arrayLikeObject)

Conclusion

I hope you find this introduction to the reduce() method of the JavaScript Array object helpful. There is another array method called reduceRight() that is identical to this method except that it processes the array in reverse order. reductRight() is a newer method, so it will not work in some older environments.

I plan on writing more articles soon that illustrate some of the operations that can be performed with the reduce() method. Until then, happy programming!

Created by Scott A. Price - © 2021