As I continue coding and learning more complex algorithms, I have realized the power of the reduce function. The MDN docs are not the easiest to digest, so in this post I will go over some useful ways to use Reduce. This post will hopefully help you better understand a very understated JS ES6 function.
If we wanted to get the sum of an array without using reduce, we would have to manually iterate through each value:
All these lines of code can be reduced into one line by utilizing the Reduce function! The Reduce function can only be called on an array. It takes in both a callback function and an initial value. The initial value can be left out if we are starting with zero.
Helper Function vs No Helper Function
The reduce function can be written in multiple ways: either including a helper callback function (for more complex logic) or writing the code out on one line. This example below illustrates both methods accomplishing the same goal: counting the number of items in the array. For sake of clarity, I will try to stick with the one-line approach.
In the one line function we pass a callback function (acc, tree) => acc +1 and the initial value 0 to the reduce function. After the first iteration of the first object in the array, the accumulator will be equal to 0 +1. Second iteration would be 1+1 and so on.
Some things to note:
The callback function will always receive an accumulator (acc) and an element of the array as the function iterates through. The accumulator is the number/object/array that is passed from one call of this callback function to the next.
The bottom function returns the same result as the top. Can you see why? If this does not make sense yet, keep reading on and look at the pattern between all these use cases.
Sum Up A Value in the Array
We can just as easily sum up the ages of the tree.
There we go! We dig one level deeper.
If we wanted to initialize this function, we could pass an integer as the initial value instead of zero. If we changed the 0 to a 10, our result would then be 98. Try it out!
Using Reduce instead of Map
In this next example, we replicate functionality of the Map function with the Reduce function. You may not utilize this in a real life scenario, but this helped me understand the Reduce function a little better. We initialize the reduce function with an empty array here as we want the tree types held in an array, but we can as easily convert this output to a string.
Creating a Dictionary
I recently discovered this trick that makes searching through an array of objects much quicker. If you’re looking for a specific object within an array, we can use reduce to create “key: value” pairs instead of looping through each object in the entire array. This saves so much time as datasets get larger. The example below will explain further.
Now each object is stored with a key value and we can retrieve any object by just knowing the key, saving so much time! Make sure to initialize with an empty object instead of array!
Looking for the Max Value
Thus far, we have been treating the callback function (accumulator) only as a value that accumulates, but in reality it is just a variable that persists through each iteration of the array. If we are looking for just the maximum value of an array, we can compare this each iteration and only keep the max (or min).
Let’s look at what is happening here.. The callback function starts with a null value the first iteration, so the accumulator is set to tree.age when checking the object item in the array (return tree.age). Then through the next iterations, the current tree.age will be compared with the stored accumulator!
I hope this little explanation allows you to get more use out of the Reduce function! The resources I linked below dive even further into these concepts.
Bonus: Flattening an Array
One last thing I will add (since it comes up often in some algorithm practice) is flattening an array. This example splits up the flatten function and utilizes some recursion. Take a look and see if you can figure out why it works!
While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited…