The Reduce Method
Tags: javascript, reduce, programming, tutorial
Published: 2022-05-07 15:08:41

In my quest to collect all the coding infinity stones in my JavaScript gauntlet, I decided to tackle the methods that perplex me. Case in point, the reduce method. Wrapping my head around how this method works was challenging for me, so what better way to master it than to write a blog post about it? As they say, if you really want to learn something, teach it.

For starters, what exactly is the reduce method? My understanding of it is, it’s a way to iterate over an array and reduce it into a single value. 

The syntax is simple enough:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1o60j20601k6lvo6fyp.png) 

You run the reduce method on an array using dot notation.
Then you call a function you want to use on each item in the array. This function takes in a minimum of two values. The first is the total value, the second is the current value. Represented above by “init”, for initial value.

You can have up to four parameters plus an initial value, but that’s a little more advanced, for today we’ll keep it simple.
Now that we have our syntax, how do we apply it?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lvkwfmlmodvjigs3tb0w.png)
 
In the example above we start out with our array called numbers. Inside are 4 integers. Here we are trying to subtract each number in the array from the number proceeding it.

In order to accomplish this task, we create our callback function, called subFunc (subtract function). We give it two parameters. The total, this amount will accumulate the results of our function being called on each array item. The second parameter is the current value, here represented as num (number).

Now that we have our array and our callback, we’ll run reduce on the numbers array using dot notation. Inside of the function call for reduce we place our callback, subFunc. Now let’s see what happens when we set our initial value to 0. We get a return value of:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2h5ugqajh5aizb22iitw.png)
 
Hmmm… that doesn’t look quite right, what happened here? Let’s console log each step of the iteration. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n94percb8d5zu7qq3u9t.png)
 
Ahh… So, our initial number we added, zero, was inserted as our total to start from. Then the first item in our array, 250, was subtracted from zero. Giving us -250. The next item, 45 was then subtracted from that. The loop continued until we end up with our final result, -370.

What would happen if we left out the initial value when calling reduce?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/idbz69ufovghoox39pvh.png)
 
The result is:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qp0odddble9az8x7tslq.png)
 
Now this looks like what we were expecting. Let’s console log to see what happened behind the scenes.
 
This time the first item in our array was used as the initial amount. The second item was then subtracted from that number and the result becomes the new total that is used in the next loop.
When the method is finished it will return the final accumulated result. In this case 130.

Now instead of an array of integers, how about an array of doubles? 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/osod0bfxzuqgs9ri113f.png)
 
Here we have an array called moreNumbers, that holds an array of float/doubles. Next, we create a callback called sumFunc (sum function), which rounds up/down each number to an integer then adds it to the accumulated total. 
Our result:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wu7ijuzbfea0h0e5n36s.png)
 
But wait, shouldn’t the final number be an integer if we’re rounding each number? Why has our function returned a double?
Let’s get to the bottom of this with a console log.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6i29bdwaiupbmp0bypgv.png)
 
Aha! Since we didn’t set an initial value, it took the first index of our array and used that instead. The call back used in a reduce method doesn’t run the calculations on the initial number, so the first item in the array was not rounded up. Therefore, it remained a double no matter how many integers we added to it.

When we add an initial value of 0, we get a different result.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vzvkmlmtsrm1q5pws015.png)
 
When the reduce method plugs 0 into the total position of the equation, it can then apply the math in sumFunc to every item in the entire array. Numbers are rounded into whole numbers and added all together. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axv4xjqjna4abgmw80r6.png)
 
Here’s an example of what it will look like if we have an initial value of 95.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/by6waryht1yr3ohfsoj4.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/23m5iipkdwhm6xgej1p2.png)
 
The reduce method is not limited to array’s of numbers however.
You can reduce an array of strings into a single string.

Here we have an array of strings. We name the string words.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tho12dmd7h2a0ppct0jj.png)
 
We build a callback function called makeSentence. It will have no initial value, so the first word will be the “sentence” when we begin. It then concatenates an empty space and the next word to our sentence.

When it’s done it will return the finished sentence.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8s8x6zu2ch2y6y8jxgb3.png)
 
One last example of our method.

Let’s say I want to keep track of how many tools a shop has sold. Every time the shop sells a tool The name of the tool is added to an array. We’ll call this array tools.

Next, we write a callback function we’ll call reduceTools.
This function starts off with an empty object. This is our total. It then checks to see if the ‘item’ parameter is a key in the object. If it is or if it isn’t, it will update the value of the key by one. If the key’s value is 0, meaning the key doesn’t exist it will add it to the object (add to the total).

Every time it comes across a key that exists it increases that keys value by 1. When it encounters a key that doesn’t exist it will add that key with an updated value of 1 to it.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxb9enzj4d5i51yf5im8.png)
 
This is what the process will look like if we console log it: 
{} hammer
1
{ hammer: 1 }
{ hammer: 1 } nails
1
{ hammer: 1, nails: 1 }
{ hammer: 1, nails: 1 } screwdriver
1
{ hammer: 1, nails: 1, screwdriver: 1 }
{ hammer: 1, nails: 1, screwdriver: 1 } hammer
2
{ hammer: 2, nails: 1, screwdriver: 1 }
{ hammer: 2, nails: 1, screwdriver: 1 } hammer
3
{ hammer: 3, nails: 1, screwdriver: 1 }
{ hammer: 3, nails: 1, screwdriver: 1 } screwdriver
2
{ hammer: 3, nails: 1, screwdriver: 2 }
{ hammer: 3, nails: 1, screwdriver: 2 } nails
2
{ hammer: 3, nails: 2, screwdriver: 2 }
{ hammer: 3, nails: 2, screwdriver: 2 } hammer
4
{ hammer: 4, nails: 2, screwdriver: 2 }
{ hammer: 4, nails: 2, screwdriver: 2 } hammer
5
{ hammer: 5, nails: 2, screwdriver: 2 }
{ hammer: 5, nails: 2, screwdriver: 2 } nails
3
{ hammer: 5, nails: 3, screwdriver: 2 }
{ hammer: 5, nails: 3, screwdriver: 2 } saw
1
{ hammer: 5, nails: 3, screwdriver: 2, saw: 1 }
So after all that the result is:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x7nitfv46iyg7or6r1nx.png)
 
We now have a single object with our tools as keys and the number sold as their values.

Awesome! We mastered the basics of the reduce method. What other ways can this method be used I wonder? 

Have fun experimenting with it and see what you can types of data you can reduce.

Thanks for coming along with me on my journey of reduce method self-discovery. 

I hope you learned something. I know I did.