[Solved] Want to sum of values with same property name in object using javascript or jquery [closed]


The solution using Array.prototype.reduce, Object.keys and Array.prototype.forEach functions:

var allreasonsids = [{reasonid: 1, reasonname: 'abc'}, {reasonid: 2, reasonname: 'def'}, {reasonid: 3, reasonname: 'ghi'}, {reasonid: 4, reasonname: 'jkl'}],
    reasonsandcount = [{reasonid: 1, quantity: 5},{reasonid: 2, quantity: 10},{reasonid: 1, quantity: 3},{reasonid: 3, quantity: 4},{reasonid: 1, quantity: 2},{reasonid: 2, quantity: 6}];

// getting sums for grouped `reasonid` items
var sums = reasonsandcount.reduce(function (a, b) {
  (a[b.reasonid]) ? a[b.reasonid] += b.quantity : a[b.reasonid] = b.quantity;
  return a;
}, {});

var result = {}, keys = Object.keys(sums);
allreasonsids.forEach(function (o) {
    this[o.reasonname] = (keys.indexOf(o.reasonid + "") !== -1)? sums[o.reasonid] : 0;
}, result);

console.log(result);

3

solved Want to sum of values with same property name in object using javascript or jquery [closed]