JavaScript, Tricks with Reduce

Useful JavaScript

In this blog I’m going to talk about the reduce method. Reduce executes a function that allows us to iterate and loop through an array, outputting a single value, which could be the sum or product of an equation, or a new array. Before moving forward, let’s declare some Arrays to use as examples.

Now with these sample arrays above, let’s create some code to showcase the capabilities of Reduce. To start, let’s use a standard loop to find the sum of our number array. It’s something familiar and has a behavior the reduce method can also replicate:

In the example above, I’m defining a variable sum with the value of ‘0’ and then running our number Array through a loop adding each number in the array and simultaneously setting the value equal to the sum. From there I have access to the sum, and can run the code with console.log(sum ,which outputs “6”.

How to get the same ‘for loop’ result using the ‘Reduce Method.’

There are two important components to a reduce method: the accumulator and the current value. An accumulator is the accumulated value in the function; in other words, similar to sum = 0 in our previous example, the accumulator starts the function with an initial value and as we pass through our array, it holds on to the value of the total. The current value is the value of the current element in the array that we are processing inside the loop. It is common to call the reduce method with two arguments. The first argument is a callback function containing an accumulator(acc) and a currentValue(cur). The second argument is optional and is the initial value of our accumulator, like 0 being the initial value of sum.

Using the reduce method to find the sum:

In the example above, we are declaring an array of numbers called “whatsLife” and a reduce method called “theMeaning” inspired by the question asked in ‘The Hitchhikers Guide to the Galaxy”, “What is the meaning of life.” The reduce method, takes the array, and passes it to an accumulator and currentValue which pass it to a callback function. The callback function returns the value of the accumulator and all instances of the currentValue.
Here is an image of what’s happening inside of the reduce method.

If we declare a reduce method without a second argument, javaScript will automatically assign the accumulator with the value of the element in index[0] and have the currentValue start as 0 by default.

We can further reduce the amount of code (no pun intended) by leaving out the curly braces, the return, and the optional initial value, to get the same result: 42.

Substituting Filter and Map with Reduce

Another amazing thing we can do with reduce, in some cases, is substitute it as an all-in-one for the filter and map method.

Let’s say we had a large set of data that we already converted into an array. And let’s call this data “pokemon.” It’s summer and hot and I want to filter through pokemon that are going to keep me cool. I’m looking for all pokemon of a certain type, and I just want to see their names and just their names. In order to do this, I will create a function that essentially lets me search for a specific type of pokemon:

In order to get all the water type pokemon in this array, we need to first filter through them. A filter method should help with this. Let’s declare a variable “water” that will hold an array of all our water pokemon data from out filter method.

With the Filter Method, I can interpolate the pokemon array using a callback function. We define a placeholder value of waterPokemon, and in our callback set a condition for our filter to collect only pokemon with the “type” matching “Water”. When we initialize water we get:

Now let’s map through this array. The map method is called on an array, and interpolates through it, grabbing all elements that specifically meet the set requirements. We could in fact tac the map method, on to the end of our filter method with dot notation. The specific data we are looking to collect is the name value of our waterPokemon data that we filtered.

This returns exactly what we are looking for. just the names of all water type Pokemon in our “pokemon” array. We could in fact get this same result by refactoring our code to take in the reduce method instead of filter and map.

Using reduce to search through our data…

Similar to the reduce method in our previous number example, we are:

  • Setting a variable equal to water
  • calling the reduce method on the “pokemon” array
    • assigning “waterArray” as the accumulator
    “waterPokemon” as the currentValue
    an empty array [] as the initial value
  • and providing a callback function as an argument, where:
    •if the currentValue(pokemon) passed into the function has a matching value of “Water” for ‘type’, then we push the name of the pokemon (pokemon.name) into the accumulator(waterArray)
  • and lastly we return the waterArray.

This gives us the desired result that we also got through filtering and mapping the array. Not necessarily less work, but one function for the price of two. I hope this was helpful. There are many more use cases for the reduce method, I found these two open many doors for iterating through large datasets.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Stephen Galvan

Stephen Galvan

A Software Engineer with a background in Education Technology and Dance. Recent grad form FlatIron Bootcamp, and passion for the arts and working with databases