Search code examples
javascriptarraysfunctional-programmingjavascript-objects

group/sum with the title


After summing up the values with same rate, i get my object as {10: 310, 101: 120, 110: 110, 120: 360}. How can i change my reduce method to get the item id written too in the grouped object so that i can identify easily.

This is my code:

var myObjArr = [
  { itemid: 12345, desc: "this is item 12345", qty: 8, rate: 101, total: 120 },
  { itemid: 22345, desc: "this is item 22345", qty: 2, rate: 120, total: 240 },
  { itemid: 52345, desc: "this is item 52345", qty: 12, rate: 10, total: 120 },
  { itemid: 42345, desc: "this is item 42345", qty: 1, rate: 110, total: 110 },
  { itemid: 52345, desc: "this is item 52345", qty: 15, rate: 10, total: 150 },
  { itemid: 52345, desc: "this is item 52345", qty: 4, rate: 10, total: 40 },
  { itemid: 22345, desc: "this is item 22345", qty: 1, rate: 120, total: 120 }
];

// var byYear = myObjArr.map(function (item) {// by date
//   var year = new Date(Date.parse(item.date)).getFullYear();
//   return { date: year, total: item.total };
// });

var myGroupedArr = myObjArr.reduce(function (memo, item) {
  memo[item.rate] = (memo[item.rate] || 0) + item.total;
  return memo;
}, {});

console.log(myGroupedArr)//{10: 310, 101: 120, 110: 110, 120: 360}

Solution

  • Just add the itemid and accumulated total to variable and wrap both of these in object.

    var myObjArr = [
      { itemid: 12345, desc: "this is item 12345", qty: 8, rate: 101, total: 120 },
      { itemid: 22345, desc: "this is item 22345", qty: 2, rate: 120, total: 240 },
      { itemid: 52345, desc: "this is item 52345", qty: 12, rate: 10, total: 120 },
      { itemid: 42345, desc: "this is item 42345", qty: 1, rate: 110, total: 110 },
      { itemid: 52345, desc: "this is item 52345", qty: 15, rate: 10, total: 150 },
      { itemid: 52345, desc: "this is item 52345", qty: 4, rate: 10, total: 40 },
      { itemid: 22345, desc: "this is item 22345", qty: 1, rate: 120, total: 120 }
    ];
    
    
    var myGroupedArr = myObjArr.reduce(function (memo, item) {
      const total = ((memo[item.rate] || {}).total || 0) + item.total;
      const {itemid} = item;
      memo[item.rate] = { total, itemid };
      return memo;
    }, {});
    
    console.log(myGroupedArr)