10 Examples To Properly Understand Javascript Reduce

The reduce method is likely the most versatile method in javascript. This makes it a very powerful tool to use and mastering it will obviously be a great asset when using the language. I however noticed that most js developers struggle with this method (From no understanding to just a mere grasp of it). I used to struggle with this method too and seldomly used it since I did not have a proper understanding of the method. Thank God it’s not the case anymore and my objective through this article is that it isn’t the case for you too.

Function prototype

reduce(callbackFn, initialValue)

reduce(calllbackFn)

Reduce takes a callback function and an initial value. The callback method takes four optional parameters which are the accumulator, the current item, the current index and the array you are looping through.

A typical reduce call will look like this: myArray.reduce((accumulator, currentItem, currentIndex, array) => {  // Your logic here }, initialValue); 

Accumulator is initialized with initialValue, accumulator is passed in as an input into every iteration. its value is updated to the returned value of each iteration and the last is finally what is returned from the reduce method

You can check more about reduce on mdn. Let’s dive into examples that will help us understand how to use reduce

1. Count number of elements in an array

  • To get the number of elements in an array, we could just use the array length method and in fact that is what you should be using whenever you need array size. We are using reduce in our example for the purpose of understanding how reduce works and demonstrate its versatility

We can see the count result is 3 which is correct

2. Sum of Ages

   Let’s make it a little harder. Now, we want to get the sum of the of all the ages 

 

 

We can see that the sum of all three ages is 91

The function above can be re-written as for better clarity.

 

In the first iteration, acc is initialized to zero so sum returns curr.age. The returned sum is assigned to acc, which is fed into the next iteration, so in the second sum is acc (previous age) + current age. Again this sum is returned so value is assigned to accumulator. In the 3rd iteration, acc’s value is the sum of the 2 previous ages and so the loop continues till the end.

3. Get Array of Names

   Now let’s get the names of each person in the array persons. This example will mimic what the map method does. For such use case it will be better to just use the map method. But for the purpose of the tutorial, we are using reduce    

 

I hope are beginning to get the logic. Let’s move to our next example.

4. Convert to id => person lookup (dictionary or Map)

  Here we will build a Map/dictionary (key => value) from the array where the keys will be the id of each element in the array and the values will be the element itself. This is done usually when we have a long list of elements which you have to iterate over several times. In this case you want to build a Map (or dictionary in some languages) for quick access    

 

 

The first implementation is a little more compact. We make use of the spread operator to populate the returned with object with acc‘s fields, adding to it a new field curr.id‘s value. As explained earlier, this newly returned object becomes acc new value in the next iteration.

The second implementation is clearer as we clearly see the assignation of curr to acc[curr.id].

Both implementations are valid, you can use the one you are more comfortable with.

5. Max age

  Now we will get the max age. This is one of the situations where reduce will be more optimal to use than the other array methods. Let’s see how it works. Here I am referring to our usual acc as max (Also to make you know you name the variables as you wish 🙂    

 

 

We initialize max to the first person’s age and iterate over, if we find the someone with age > max, we return the age which becomes max‘s new value in the next iteration. Straight forward right !

6. Min age

  This example is very similar to max age above. So I thought I should leave you guys try your hand on this 🙂 Do not hesitate to leave a comment below if you need help or even to present your own solution   

7. Find by Name

  We are to find a person with a certain name, let’s say “PETER”. Our reduce function should return the person object if the person is found and return null otherwise. I will recommend you use the array find method for such use case in your code. But for the purpose of this tutorial we use reduce    

 

 

 

The object with name PETER is returned successfully. Now let’s check with a name that doesn’t exist and see the result

 

 

As you can see we get null. Remember however to that the find method is more optimal for this use case.

8. All Over 18 ?

  Let’s find out if every person in our array is above 18 years. results should be true if everyone is above 18 and false otherwise    

 

 

 

We have our expected value. As we can see. Mary is 16. So the result is false. Not everyone is above 18. I’m leaving it to you to run the case where everyone is above 18 and see the results. Let’s move to the next.

9. Any above 18 ?

  Unlike the previous example, here, we want to find out if at least one person is above 18 years and that suffices to return true . If no one if above 18, results should be false
   

 

 

 

 

Our results value is true since we have 2 people above 18 so the result is true. Like the example above I am leaving the false case for you to test 🙂

10. Count number of occurrences

 Let’s drift a little from our array of persons. Now we are going to work with an array of orders. We are going to count the number of occurrences of status values in each order. The order can have one of 3 status; pending, shipping or cancelled.  

 

 

 

We provide two implementations above. The first implementation is a one line method and makes use of the spread operator. If you are not used to the spread operator, the second implementation is more explicit.

As we can see, acc is initialized to an empty object, in the callback function we check if the acc has the field curr.status (whose value could be ‘pending’, ‘shipping’ or ‘cancelled’). If it does not the field is added and it’s value set to 1 else the value is simply incremented

11. Flatten

I am really confident by now you fully understand how reduce works. In this last example we will flatten an array with nested array values. A practical scenario: Imagine you have a folder that contains files and other folders that contains files too… and you want an array of just the files… Hope you get the idea.

We are going to use recursion to solve this.

 

 

 

 

Conclusion

We have come to the end of this tutorial. Hope it was helpful and you feel more confident in using reduce in your projects.

I will like to say a big Thank you to @Leigh Halliday whose video made me understand reduce and which is the basis for this article.

Do not hesitate to write us in the comment section to ask your questions, we will be there to reply you 

 

 

 

 

 

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *