reduce an array of objects code example

Example 1: 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 2: creating array of objects usinng reduce js

const posts = [
    {id: 1, category: "frontend", title: "All About That Sass"},
    {id: 2, category: "backend", title: "Beam me up, Scotty: Apache Beam tips"},
    {id: 3, category: "frontend", title: "Sanitizing HTML: Going antibactirial on XSS attacks"}
];

const categoryPosts = posts.reduce((acc, post) => {
    let {id, category} = post;
    return {...acc, [category]: [...(acc[category] || []), id]};
}, {});

Example 3: reduce object to array javascript

var arr = [{x:1},{x:2},{x:4}];

arr.reduce(function (a, b) {
  return {x: a.x + b.x}; // returns object with property x
})

// ES6
arr.reduce((a, b) => ({x: a.x + b.x}));

// -> {x: 7}

Example 4: js reduce

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

Example 5: .reduce mdn

arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])

Example 6: reduce javascript acc became numeber insted array

const secondArray = [1, 2, 3].reduce((acc, item) => {
    acc.push(1);

    return acc;
}, []);

console.log(secondArray);