JavaScriptsreduceis one of the most useful array methods that should be in a developers arsenal.
Its a cleaner way of iterating over and processing the data stored in an array.
It’s free, every week, in your inbox.

Lets get started then!
The reducer function takes four arguments:accumulator,currentValue,currentIndex, andarray.
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 accumulators value is updated to the returned result.
Here, we are not passing aninitialValueargument.

The final output of this function is10.
Next, lets see how it works when aninitialValueis passed.
This function outputs the value22.

So what are the situations in which we can benefit from this uniqueness?
The only difference is we have to pass 0 for theinitialValueparameter.
If the current value is not an array, we simply concatenate the value with the final flattened array.

We can use thereducemethod for this task.
Then we push each country object to the array stored by their respective continents.
It will reduce the completion time because now you only iterate through the array only once, not twice.

The same scenario implemented using reduce looks like this.
You have to pass an empty array as the initial value to get this result.
First, we peek if the reduce method was called on a null or undefined object.

Then we verify if the passed callback is a function.
After the initial throw in 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 might see that it uses aforloop to iterate through the array under the hood.

However, note that you shouldnt 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.
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.
Sign up for updates on everything related to programming, AI, and computer science in general.
Also tagged with





