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

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

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

Creating a Dictionary

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

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!

Conclusion

Bonus: Flattening an Array

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