DEV Community

Cover image for Array Method in JavaScript:  Reduce
Donny
Donny

Posted on

Array Method in JavaScript: Reduce

Let’s review one of my favorite advanced array methods in JavaScript: Reduce.

What Does Reduce Do?

Imagine taking a bunch of ingredients from a recipe and tossing them one by one into a pot. Apply heat to that pot. After the pot cooks for a bit, you’ll be left with a marvelous stew.

That’s basically what happens in the reduce method. We take a bunch of items (elements of an array). Throw them into a pot (an accumulator) and apply heat (logic) . Finally, we are left with our result--a yummy dish.

Let’s take a simple example:

We start with our dish’s ingredients: an array of 4 integers. Let’s call our array “ourIngredients.”


const ourIngredients = [ 1, 2, 3, 4]

Enter fullscreen mode Exit fullscreen mode

Our recipe calls for us to take our ingredients, add them all together and come out with a total. So given our ingredients: 1, 2, 3, 4; we’re hoping to use our reduce recipe to end up with 10 (1 + 2 + 3 + 4).

So let’s set it up.

We’ll need a variable “stove” to be assigned to the cooking instructions.


const ourIngredients = [ 1, 2, 3, 4]

const stove

Enter fullscreen mode Exit fullscreen mode

The stove will need a pot, then need to take each “ingredient” in turn:


const ourIngredients = [ 1, 2, 3, 4] 

const stove = ( pot, ingredient ) =>

Enter fullscreen mode Exit fullscreen mode

Now we have to tell the stove what to do with the pot and the ingredient. In our case, we just want to add each ingredient to the pot in order to get our cumulative total:


const ourIngredients = [ 1, 2, 3, 4] 

const stove = ( pot, ingredient ) => pot + ingredient

Enter fullscreen mode Exit fullscreen mode

Let’s put it all together. All that remains is to “call” our stove on the list of ingredients. The magic word we’ll use is “reduce”: (We’ll console.log our result)


const ourIngredients = [ 1, 2, 3, 4] 
// In techno talk, we have:
// 1) declared an arrow function and named it ‘stove’
// 2) passed in 2 parameters: ‘pot’ and ‘ingredient’ 
       // (pot, ingredient)
// 3)  told pot to just keep adding the given ingredient
//    to the pot:   pot + ingredient

const stove = ( pot, ingredient ) => pot + ingredient

//take the ingredients, call the reduce method
// and pass in our instructions (stove)
console.log(ourIngredients.reduce(stove));  // 10

Enter fullscreen mode Exit fullscreen mode

That is the basic. Now let’s get a little fancier.

Our current example assumes we’re starting with an empty pot, that is, at 0. But what if our pot already had something in it--let’s say an integer “5” was already in the pot before we started cooking. In that case, we would expect to get 15 at the end of our session (10 + 5)

Let’s see how to add something to the pot before cooking with “ourIngredients:”


const ourIngredients = [ 1, 2, 3, 4] 

const stove = ( pot, ingredient ) => pot + ingredient

//But there is a 5 already in the pot:
console.log(ourIngredients.reduce(stove, 5));  // 15

Enter fullscreen mode Exit fullscreen mode

Before I leave you for today, let’s ratchet it up a couple of notches with a more challenging example. This next example comes up from time to time in coding challenges:

Say we’re given an array of names:

const names = [ Desmond, Orlando, Leticia, Desmond, Shane, Desmond,  Madison, Leticia]
Enter fullscreen mode Exit fullscreen mode

We need to find out how many times each name occurs and end up with a object like this:

const names = [ Desmond, Orlando, Leticia, Desmond]

// convert the array into an object and count
// the occurrence of each element:
{

Desmond: 3,
  Orlando: 1,
  Shane: 1,
  Madison: 1,
  Leticia: 2
}

Enter fullscreen mode Exit fullscreen mode

Let’s do it by first setting up our stove. We know we’ll need a pot and an ingredient as parameters. When it’s all done, we’ll want to pop the pot off the stove by using a “return” statement:


const stove = ( pot, ingredient) => {



return pot

}
Enter fullscreen mode Exit fullscreen mode

Now comes the logic. If the ingredient is already in the pot, all we have to do is increment its count (Its count is the ingredient’s value)


const stove = ( pot, ingredient) => {

if (pot[ ingredient ]) {
  pot[ ingredient ]++
}

return pot

}
Enter fullscreen mode Exit fullscreen mode

Else, we know the ingredient is not in the pot, so we can set its value or count to 1:


const stove = ( pot, ingredient) => {

if (pot[ ingredient ]) {
  pot[ ingredient ]++
} else {
  pot[ ingredient ] = 1
}

return pot

}
Enter fullscreen mode Exit fullscreen mode

Now let’s bring it all together!

let’s take our “names” array, call our magic “reduce” method and tell it to use our stove method:


//almost done…..
names.reduce(stove)
Enter fullscreen mode Exit fullscreen mode

Oops! Almost done. We forgot two things. Firstly, we want to console.log the results:


// REALLY almost done…..
console.log(names.reduce(stove))
Enter fullscreen mode Exit fullscreen mode

AND, we need to tell our reduce method that there was something already in the pot when we began cooking. What was that? An empty object, {} !!!! We’ll need that empty object to hold the transformed array:


// Now we’re done.  Notice the empty array after “stove”
console.log(names.reduce(stove), {} )
Enter fullscreen mode Exit fullscreen mode

And there you are: a primer to the “reduce” method in JavaScript. Have a look at the MDN with the full treatise on “reduce” there are some even wilder things you can do with it!

Here’s the link to the MDN article on “reduce”

Keep on cooking up your dreams with code!

Namaste!

Top comments (0)