Answers for "stackoverflow array reduce"

1

stackoverflow array reduce

const arr = [{x:1}, {x:2}, {x:4}];
arr.reduce(function (acc, obj) { 
    return acc + obj.x; 
  }, 0); //result = 7

// acc = accumulator (result from the last iteration)
// obj = iterated object from arr
// 0 = initial value for the accumulator(acc)

// Arrow function =>
arr.reduce((acc, obj) => acc + obj.x, 0);

// 0 + 1 = 1 
// 1 + 2 = 3 
// 3 + 4 = 7;
// *note when multiplying use a initial value of 1 
// beceause => (0 * 2 = 0)
Posted by: Guest on July-28-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language