js reduce code example

Example 1: javascript sum of array

const sum = arr => arr.reduce((a, b) => a + b, 0);

Example 2: how to flatten array with reduce in javascript

let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(accumulator, currentValue) {
    return accumulator.concat(currentValue)
  },
  []
)
// flattened is [0, 1, 2, 3, 4, 5]

Example 3: javascript reduce sum

arrSum = function(arr){  return arr.reduce(function(a,b){    return a + b  }, 0);}

Example 4: javascript reduce array of objects

var objs = [
  {name: "Peter", age: 35},
  {name: "John", age: 27},
  {name: "Jake", age: 28}
];

objs.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue.age;
}, 0); // 35 + 27 + 28 = 90

Example 5: js reduce

let newArray = array.reduce( (acc, element, index, originalArray) => {
    // return acc += element
}, initialValue)

Example 6: js reduce

Sum array elements:
let myArr = [1,2,3,-1,-34,0]
return myArr.reduce((a,b) => a + b,0)