CYBER MONDAY WEEK 🤑 Get 30% off your TNW for Startups or Scaleups packages when you use code CYBER30 only until December 4 →

This article was published on February 26, 2021

The ins and outs of JavaScript reducer — a simple, yet powerful array method


The ins and outs of JavaScript reducer — a simple, yet powerful array method Image by: Unsplash

JavaScript’s reduce is one of the most useful array methods that should be in a developer’s arsenal. Introduced in ES5, it’s somewhat similar to for…each and map methods that are used with arrays, but improves on their performance and simplicity in specific situations.

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 versionsand 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!

Javascript reduce method parameters

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.

An example of Javascript array reduce method in action:

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 final output of this function is 10.

Next, let’s see how it works when an initialValue is passed.

This function outputs the value 22.

When to use JavaScript’s reducer

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.

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 the isArray method, we recursively call the flattenArray function 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 the reduce method 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 the filter method 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 array reduce method 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 the accumulator array. 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 passed initialValueto 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 a for loop 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 with the forEach , map, and filter array methods. So you should know to pick the situations that can be solved optimally using the reduce method.

This article was originally published on Live Code Stream by Juan Cruz Martinez (twitter: @bajcmartinez), founder and publisher of Live Code Stream, entrepreneur, developer, author, speaker, and doer of things.

Live Code Stream is also available as a free weekly newsletter. Sign up for updates on everything related to programming, AI, and computer science in general.

Get the TNW newsletter

Get the most important tech news in your inbox each week.

Also tagged with


Published
Back to top