The reduce method executes a callback function that we provide on each element stored in an array and outputs the final value the operation generates. It’s a cleaner way of iterating over and processing the data stored in an array.
Currently, it’s supported by all of the major browser versions, and is available in Node.js from version 10.0 upwards.
Today, we are going to explore this reduce method; more specifically, we’ll go through how and when to use it in different scenarios.
Let’s get started then!
The reduce method accepts two arguments: a reducer function for the array that is used as a callback, and an optional initialValue argument. The reducer function takes four arguments: accumulator, currentValue, currentIndex, and array.
The This reduce method does the same job as the following for…each loop, but with fewer lines of code.
How does the reduce method achieve it using these parameters?
The value returned by the reducer function is assigned to the accumulator variable. In each iteration through the array items, the accumulator’s value is updated to the returned result. At the end of the iteration, the final value of the accumulator is returned as the output of the reduce function.
If an initialValue argument is passed, the first time the reducer function is executed, the accumulator will be equal to initialValue and the currentValue will be equal to the first element stored in the array. If an initialValue is not passed, the accumulator will be equal to the first value of the array and currentValue will be equal to the second.
Let’s see how the values of each of these parameters change every time the callback function is called in the following example. Here, we are not passing an initialValue argument.
The reduce method provides a unique way to iterate through items in an array and process them. So what are the situations in which we can benefit from this uniqueness?
Calculate the sum of values in an array
This is similar to what we did in previous examples. The only difference is we have to pass 0 for the initialValue parameter.
Flatten an array
If we have an array of arrays, we can use the reduce method to flatten it and create a single array without nested arrays.