Can anyone explain me higher level examples when to use reduce() method in javascript
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
Can anyone explain me higher level examples when to use reduce() method in javascript
3
Answers
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:
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):
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!
One scenario – E-commerce cart. You are adding items to a cart and storing them in an array.
You want to calculate the total price – you can use reduce in this scenario.
Any time you use a
for
loop to iterate over an array and sum its values, you can use reduce."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 usingreduce
in higher-order functions—including some staples of functional programming likecompose
andpipeline
.