Londonchiropracter.com

This domain is available to be leased

Menu
Menu

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

Posted on February 26, 2021 by admin

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

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.

Source

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • LG Electronics and Nvidia are in talks on robotics, AI data centres, and mobility
  • Sequoia is giving away the hardware for an AI project it cannot invest in. That is the point.
  • Trump says Anthropic Pentagon deal is ‘possible’, weeks after blacklisting the company as a national security risk
  • Samsung and IKEA just made the $6 smart home real, and your TV is already the hub
  • OpenAI recruits Cognizant and CGI to take Codex into enterprise software shops worldwide

Recent Comments

    Archives

    • April 2026
    • March 2026
    • February 2026
    • January 2026
    • December 2025
    • September 2025
    • August 2025
    • July 2025
    • June 2025
    • May 2025
    • April 2025
    • March 2025
    • February 2025
    • January 2025
    • December 2024
    • November 2024
    • October 2024
    • September 2024
    • August 2024
    • July 2024
    • June 2024
    • May 2024
    • April 2024
    • March 2024
    • February 2024
    • January 2024
    • December 2023
    • November 2023
    • October 2023
    • September 2023
    • August 2023
    • July 2023
    • June 2023
    • May 2023
    • April 2023
    • March 2023
    • February 2023
    • January 2023
    • December 2022
    • November 2022
    • October 2022
    • September 2022
    • August 2022
    • July 2022
    • June 2022
    • May 2022
    • April 2022
    • March 2022
    • February 2022
    • January 2022
    • December 2021
    • November 2021
    • October 2021
    • September 2021
    • August 2021
    • July 2021
    • June 2021
    • May 2021
    • April 2021
    • March 2021
    • February 2021
    • January 2021
    • December 2020
    • November 2020
    • October 2020

    Categories

    • Uncategorized

    Meta

    • Log in
    • Entries feed
    • Comments feed
    • WordPress.org
    ©2026 Londonchiropracter.com | Design: Newspaperly WordPress Theme