skip to Main Content

Can anyone explain me higher level examples when to use reduce() method in javascript

3

Answers


  1. Reduce is the ‘swiss army knife’ of functional array methods, basically everything you can do with a map or filter can be done with reduce too (although with a bit more effort), but reduce can also do a lot of other things.

    Reduce, like map and filter "loops" through every item in array. It has an accumulator and a current value, you are expected to always return the new value for the accumulator.

    You could think of it as reducing a number of values (the array) to a single value, the accumulator.

    You can set an initial value for the accumulator as the second argument to reduce, or don’t do this. If you don’t the first value in the array will be used as the initial value of the accumulator.

    About the simplest thing you can do with reduce is calculating the sum of an array of numbers:

    [1,2,3].reduce((a,c) => a + c)
    

    But what about if you wanted to create a new array, start off with an initial value for the accumulator that is an array. Here we reverse an array (there is a built in method for that too – reverse – I know):

    ['here','are','some','words'].reduce((a,c) => a.unshift(c) && a, []);
    

    Basically reduce can do almost anything any other array method can and other things too – up to your imagination/the problem you are solving. That doesn’t mean that you should always use reduce – the syntax will be simpler if you can get away with a map, filter or other method (like reverse for my example above). But if you have run out of ‘simpler’ options it should be your weapon of choice. So learn how to use it!

    Login or Signup to reply.
  2. One scenario – E-commerce cart. You are adding items to a cart and storing them in an array.

    itemsInCart = [{name: "Shoes", quantity: 2, unitPrice: 10}, {name: "Hats", quantity: 7, unitPrice: 5}, {name: "Pants" quantity: 1, unitPrice: 14}]
    

    You want to calculate the total price – you can use reduce in this scenario.

    total = itemsInCart.reduce((total, item) => total + item.unitPrice * item.quantity, 0)
    

    Any time you use a for loop to iterate over an array and sum its values, you can use reduce.

    Login or Signup to reply.
  3. "Higher-level" is relative, but if you already understand the reduce examples on MDN (and/or on javascript.info), then JavaScript Allongé has some great examples of using reduce in higher-order functions⁠—including some staples of functional programming like compose and pipeline.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search