Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

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)

Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #stackoverflow #array #reduce
ADD COMMENT
Topic
Name
8+8 =