As a front end developer, it’s basic and routine to handle arrays. There are lots of methods can be used in array, reduce is one of my favorite array method. I used to handle array with array method forEach when being a newbie. But found that reduce is more powerful than other array methods.
How To Use Reduce?
Let’s look parameters in reduce:
accumulator: Value from previous call to callback function, it accumulate result for every iteration.
currentValue: Value of current array element
currentIndex: Index of current array element (Optional)
array: The array to traverse (Optional)
initialValue:A optional value for the first time when the callback function is called. If it is not specified, the first of element in array will be initial value.
It may sounds oblique, let’s try some scenarios.
Accumulation
What if we want to get sum of all numbers in a array? A Javascript beginner may write code like this.
It’s equivalent to
Actually we don’t have to specify initial value, so 1 will be initial value.
Besides accumulation, there are several ways to use reduce.
Make HashMap
Get specific Data (filter)
Flat Arrays
Concatenate Objects
Sort Keys in Object
It’s surprise me that reduce works not only for objects but also for type of chained data.
Dynamic Promise chain
While dealing with dynamic and unpredictable things, reduce can be a good choice.
Making ListNode
For a Javascript newbie it maybe convoluted in using reduce. While understanding how it works, we can write more clear and elegant code!