kingsdisease
kingsdisease

Reputation: 1

how to sum property values of arrays created by reduce

This is my code :

var array = 
  [
    {
      id: "BG",
      qty: 100
    }, 
    {
      id: "BG",
      qty: 35
    }, 
    {
      id: "JP",
      qty: 75
    },
    {
      id: "JP",
      qty: 50
    }
 ];


var result = array.reduce((obj, cur) => (obj[cur.id] = [...(obj[cur.id] || []), cur], obj), {})
console.log(result);

What I would like to do is group the array into sub arrays based on the ID's which the array.reduce does. But now I want to sum the total of the qty.

So I'm expecting values the total qty for BG to be = 35 and the total qty for JP to be 125, and then I want to be able to run math conditions on those numbers

Upvotes: 0

Views: 48

Answers (1)

IT goldman
IT goldman

Reputation: 19511

It really have been asked before, but by the time I'd search for it I could also write it. It's not that long.

var array = [{
    id: "BG",
    qty: 100
  },
  {
    id: "BG",
    qty: 35
  },
  {
    id: "JP",
    qty: 75
  },
  {
    id: "JP",
    qty: 50
  }
];

var result = Object.values(array.reduce(function(agg, item) {
  agg[item.id] = agg[item.id] || {
    id: item.id,
    qty: 0
  }
  agg[item.id].qty += item.qty;
  return agg;
}, {}));

console.log(result);

Upvotes: 1

Related Questions