Skip to content Skip to sidebar Skip to footer

Want To Sum Of Values With Same Property Name In Object Using Javascript Or Jquery

Hi I want to do sum of the quantity for each reason name.And I have 2 arrays as per below. var allreasonsids=[]; allreasonsids = [ {reasonid: 1, reasonname: abc}, {reasonid

Solution 1:

You can use reduce() and filter() to return object as result.

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

var 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}
];

var result = allreasonsids.reduce(function(r, e) {
  var quant = reasonsandcount.filter(function(a) {
    return e.reasonid == a.reasonid
  }).reduce(function(re, el) {
    return re + el.quantity
  }, 0)
  r[e.reasonname] = quant;
  return r
}, {})

console.log(result)

You can also just use reduce() and forEach() loop.

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

var 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}
];

var result = allreasonsids.reduce(function(r, e) {
 var quant = 0;
 reasonsandcount.forEach(el => el.reasonid == e.reasonid ? quant+=el.quantity : 0);
 r[e.reasonname] = quant;
 return r
}, {})

console.log(result)

Solution 2:

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` itemsvar 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);

Post a Comment for "Want To Sum Of Values With Same Property Name In Object Using Javascript Or Jquery"