Javascript Reduce

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.

Sum Up A Value in the Array

We can just as easily sum up the ages of the tree.

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.

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).

Conclusion

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!

--

--

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