Wednesday, 23 August, 2017 UTC


Summary

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:-
var numbers = [1,2,3,4,5,6,7,8]
var total = numbers.reduce((sum, num)=>{
  console.log("The Sum is equal to "+sum)
  return sum+num;
});
console.log("The total of the entire array is "+total)

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.
var numberArrays = [[1,2],[3,4],[5,6],[7,8]];
var result = numberArrays.reduce((a,b)=>{
  return a.concat(b);
});
console.log("The result for this is as follows "+result);
The post How to use reduce() in JavaScript Arrays appeared first on The Web Juice.