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:
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?
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:
Hmmm… that doesn’t look quite right, what happened here? Let’s console log each step of the iteration.
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?
The result is:
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?
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:
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.
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.
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.
Here’s an example of what it will look like if we have an initial value of 95.
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.
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.
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.
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:
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.
Top comments (0)