Reducing an array using a function against an accumulator from left to right is the use of the reduce(), It’s useful in a situation where you have a lot of calculations to be done across an array and reduce it out to a single value. In this case, it is good to remember that the accumulator starts with the value of zero and then carries forward the resultant values. Let’s see this in action.

Summing up Numbers in Array using Reduce()

A simple array as shown contains numbers which when acted upon with the function and accumulator results in the sum of all the numbers together. Note that the accumulator is 0 when we start the process.You can see this in action below:-

Flattening a list of elements in an array using Reduce()

Flattening is mostly required in various places where we want to perform some operations in the list of lists and proceed with one single result. We will be seeing Array or Arrays and then try to do some operation inside each array and then produce the result again.

Also published on Medium.

Join our 2500+ fellow readers

Join our 2500+ fellow readers

Joining our mailing list will for sure keep you at the top of Web Development Ecosystem. Connect with us and also other fellow developers.

You have Successfully Subscribed!

Pin It on Pinterest

Share This