Reduce JavaScript

let arr = [1,3,5,7,9] 
let sum = 0
for (let i=0; i<arr.length; i++){sum += arr[i]}
arr.reduce(callback, initialValue)

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 shown below illustrates both methods accomplishing the same task: counting the number of items in the array. For easier visualization we will try to keep 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

The Reduce Function is so powerful that we can even replicate the functionality of the Map Function with the reduce function. Maybe it's not something that we are going to use in a real life scenario, but it makes it easier to understand the functionality of Reduce. 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.

Searching for 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 blog allows you to get more use out of the Reduce function. AS we can see reduce is a very powerful functions to use for a Developer. Below i'll share some resources so we can understand better reduce.

--

--

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