The ins and outs of JavaScript reducer — a simple, yet powerful array method
Javascript reduce method parameters
Thereducemethod accepts two arguments: a reducer function for the array that is used as a callback, and an optionalinitialValueargument. The reducer function takes four arguments:accumulator,currentValue,currentIndex, andarray.
An example of Javascript arrayreducemethodin action:
The Thisreducemethoddoes the same job as the followingfor…eachloop, but with fewer lines of code.
How does thereducemethod achieve it using these parameters?
The value returned by the reducer function is assigned to theaccumulatorvariable. 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 thereducefunction.
If aninitialValueargument is passed, the first time the reducer function is executed, theaccumulatorwill be equal toinitialValueandthecurrentValuewillbe equal to the first element stored in the array. If an initialValue is not passed, theaccumulatorwill be equal to the first value of the array andcurrentValuewillbe 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 aninitialValueargument.
The final output of this function is10.
Next, let’s see how it works when aninitialValueis passed.
This function outputs the value22.
When to use JavaScript’s reducer
Thereducemethod 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 theinitialValueparameter.
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.
We pass an empty array as the initial value so the items in the first array are concatenated with it to create a flattened array.
If the first array has more than one level of nested arrays, we can recursively call the reduce function to flatten and then concatenate them with the final array.
If the current value accepted by the callback is an array, as verified using theisArraymethod, we recursively call theflattenArrayfunction on it. If the current value is not an array, we simply concatenate the value with the final flattened array.
Grouping an array of objects by a property
Assume that we have an array of objects that are basically the names of countries — and we want to group each country in the array according to their continents. We can use thereducemethod for this task. Check out the code snippet below:
Inside the callback function, we create a new key for each continent that is not in the groupedCountries map and assign an empty array as its value. Then we push each country object to the array stored by their respective continents.
Using reduce() in place of filter().map()
In JavaScript, we use thefiltermethod to filter items stored in an array using a callback. We use the map method to create a new array using the old array using the logic passed inside a callback. Sometimes we have to use these two methods, one after the other to create a new array with the results we filter using some conditions.
Instead of using two array methods, you can use the JavaScript arrayreducemethod to complete the same task. It will reduce the completion time because now you only iterate through the array only once, not twice.
For example, let’s take the following scenario where we want to create an array of square roots of numbers greater than 30.
The same scenario implemented using reduce looks like this.
Inside the callback, we simply check if the number is greater than 30 and add its square root to theaccumulatorarray. You have to pass an empty array as the initial value to get this result.
Build your own reducer
In this section, we are going to implement the reducer function on our own to see how things work under the hood. This will give you a better idea of when to use the JavaScript reducer for optimal performance in your program.
First, we check if the reduce method was called on a null or undefined object. Then we check if the passed callback is a function.
After the initial type checks, we assign the passedinitialValueto the accumulator. Then we loop through the array and call the callback for each item in the array. At the end of execution, we have to return the accumulator value.
We are using this implementation only to help you understand how the reduce method actually works. For example, you can see that it uses aforloop to iterate through the array under the hood.
However, note that you shouldn’t use this implementation in your production code. In fact, prototyping methods to JavaScript standard types is a bad coding practice you should never indulge in.
I hope this knowledge will help you to identify problems that can be resolved with the reducer in the future. Some of these use cases overlap withtheforEach,map, andfilterarray methods. So you should know to pick the situations that can be solved optimally using thereducemethod.
Thisarticlewas originally published onLive Code StreambyJuan Cruz Martinez(twitter:@bajcmartinez), founder and publisher of Live Code Stream, entrepreneur, developer, author, speaker, and doer of things.
Live Code Streamis also available as a free weekly newsletter. Sign up for updates on everything related to programming, AI, and computer science in general.