The professionals and cons of the JavaScript Reducer – a easy however highly effective array technique

JavaScript flattening is one of the most useful array methods a developer’s arsenal should have. Introduced in ES5, it is somewhat similar to each and the Map method used with arrays, but improves their performance and simplicity in certain situations.

The reduction method performs a callback function that we provide for each item stored in an array and returns the final value that the operation generates. This is a cleaner way to iterate and process the data stored in an array.

Currently it is supported by all common browser versions, and is available in Node.js from version 10.0.

Today we are going to examine this reduction method;; In detail, we will explain how and when to use it in different scenarios.

Let’s start then!

Javascript reduces method parameters

The reduction method takes two arguments: a reduction function on the array used as a callback, and an optional one Original value Argument. The reduction function accepts four arguments: Accumulator, Current value, currentIndex and array.

An example of a Javascript array to reduce method in action:

The this to reduce method does the same job as the following for … each loop, but with fewer lines of code.

How does it work to reduce Method achieve it with these parameters?

The value returned by the reducing function is assigned to the accumulator Variable. With each iteration through the array elements, the value of the accumulator is updated to the returned result. At the end of the iteration, the end value of the accumulator is returned as the output of the to reduce function.

When a Original value The argument is passed when the reduction function is run for the first time Battery will be the same Original value and the Current value become be equal to the first element stored in the array. If an initialValue is not passed, the The accumulator corresponds to the first value of the array and the current value become be equal to the second.

Let’s see how the values ​​of each of these parameters change each time the callback function is called in the following example. We can’t get past one here Original value Argument.

The final output of this function is 10.

Next let’s see how it works if one Original value is passed.

This function outputs the value 22.

When does JavaScript use the reducer?

The reduction method provides a unique way of iterating and processing elements in an array. In which situations can we benefit from this uniqueness?

Calculate the sum of the values ​​in an array

This is similar to what we did in the previous examples. The only difference is that we have to pass 0 for that Original value Parameter.

Reduce an array

When we have an array of arrays we can use the reduction method to reduce it and create a single array with no nested arrays.

We’re passing an empty array as the initial value so that the elements 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 reduction function to reduce it and then concatenate it with the final array.

If the current value accepted by the callback is an array, as verified with the isArray method, we call the flattenArray function recursively. If the current value is not an array, we simply concatenate the value with the final flattened array.

Grouping an array of objects according to a property

Suppose we have a number of objects, which are basically the names of countries – and we want to group each country in order by its continents. We can use the reduction method for this task. Take a look at the following code snippet:

Inside the callback function, we create a new key for each continent that is not in the groupedCountries map and assign its value to an empty array. Then we move each country object into the array that is stored on the respective continents.

Use redu () instead of filter (). Map ()

In JavaScript we use the filter method to filter elements 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 in a callback. Sometimes we need to use these two methods in turn to create a new array of the results that we filter under certain conditions.

Instead of using two array methods, you can use the JavaScript array collapse method to do the same task. This will reduce completion time because you will now only loop through the array once, not twice.

For example, let’s take the following scenario where we want to create an array of square roots with numbers greater than 30.

The same scenario implemented with Reduce looks like this.

Inside the callback, we just check if the number is greater than 30 and add its square root to the accumulator array. You must 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 collapse function ourselves 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 whether the reduction method was called on a null or undefined object. Then we check if the callback passed is a function.

After the initial type test, we assign the transferred initialValu to the accumulator. Then we iterate through the array and call the callback for each element in the array. At the end of the execution we need to return the accumulator value.

We are only using this implementation to help you understand how the reduction method actually works. For example, you can see that a for loop is being used to iterate through the array under the hood.

Note, however, that you shouldn’t use this implementation in your production code. In fact, prototyping methods for standard JavaScript types are bad coding practice that you should never indulge in.

I hope this knowledge will help you identify problems that the reducer can solve in the future. Some of these use cases overlap with the for each , Card and Filter array methods. So you should know which situations can be optimally solved with the reduction method.

This items was originally published on Live code stream by Juan Cruz Martinez placeholder image (Twitter: @bajcmartinez), Founder and editor of Live Code Stream, entrepreneur, developer, author, speaker and maker 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.

Read on: MyHeritage’s new AI tool turns photos of the dead into annoying videos

Leave your vote

0 points
Upvote Downvote

Related Articles

Log In

Forgot password?

Forgot password?

Enter your account data and we will send you a link to reset your password.

Your password reset link appears to be invalid or expired.

Log in

Privacy Policy

Add to Collection

No Collections

Here you'll find all collections you've created before.