Answers for "how to group by and sum an array of objects"

1

sum of array of objects javascript

var accounts = [
  { name: 'James Brown', msgCount: 123 },
  { name: 'Stevie Wonder', msgCount: 22 },
  { name: 'Sly Stone', msgCount: 16 },
  { name: 'Otis Redding', msgCount: 300 }  // Otis has the most messages
];

// get sum of msgCount prop across all objects in array
var msgTotal = accounts.reduce(function(prev, cur) {
  return prev + cur.msgCount;
}, 0);

console.log('Total Messages:', msgTotal); // Total Messages: 461
Posted by: Guest on May-11-2021
0

js sum array of objects to new group

var array = [
  { Id: "001", qty: 1 }, 
  { Id: "002", qty: 2 }, 
  { Id: "001", qty: 2 }, 
  { Id: "003", qty: 4 }
];

var result = [];
array.reduce(function(res, value) {
  if (!res[value.Id]) {
    res[value.Id] = { Id: value.Id, qty: 0 };
    result.push(res[value.Id])
  }
  res[value.Id].qty += value.qty;
  return res;
}, {});

console.log(result)
Posted by: Guest on October-08-2020

Code answers related to "how to group by and sum an array of objects"

Code answers related to "Javascript"

Browse Popular Code Answers by Language