Sum quantities in objects with identical properties

Asked

Viewed 30 times

1

I’m doing a job and I came across a question that is apparently quite simple, but I’m not getting it. I need to do a reduce (or could be otherwise as well) to sum the quantity of items with the identical property. For example:

let arr = [
  {id: "xxx", amount: 2}, 
  {id: "xxx", amount: 7}, 
  {id: "yyy", amount: 2},
  {id: "yyy", amount: 5},
  {id: "zzz", amount: 5}
];

For this Array above, I would need to get the following result:

[
  {id: "xxx", amount: 9},
  {id: "yyy", amount: 7},
  {id: "zzz", amount: 5}
]

1 answer

3


You really need to use reduce? A loop simple solves:

let arr = [
  {id: "xxx", amount: 2}, 
  {id: "xxx", amount: 7}, 
  {id: "yyy", amount: 2},
  {id: "yyy", amount: 5},
  {id: "zzz", amount: 5}
];

let result = {};
for (const e of arr) {
    if (result[e.id]) { // id já existe, somar amount
        result[e.id].amount += e.amount;
    } else { // id não existe, criar o objeto com o amount inicial
        result[e.id] = { id: e.id, amount: e.amount };
    }
}

console.log(Object.values(result));

The idea is to create an object whose keys are the id's, and values are the objects that will have the amount'accumulated amounts.

If the id does not yet exist in this object, I put the amount initial. If the id already exists, just add to the amount existing.

Then just take the values of this object, that the result will be an array containing the objects that have the accumulated values.


But of course, you can also do with reduce:

let arr = [
  {id: "xxx", amount: 2}, 
  {id: "xxx", amount: 7}, 
  {id: "yyy", amount: 2},
  {id: "yyy", amount: 5},
  {id: "zzz", amount: 5}
];

let result = arr.reduce(function(acc, val) {
    if (acc[val.id]) {
        acc[val.id].amount += val.amount;
    } else {
        acc[val.id] = { id: val.id, amount: val.amount };
    }
    return acc;
}, {});
console.log(Object.values(result));

The idea is the same as the previous code, but all the work is done in the function of callback.

  • 1

    It helped a lot. The two codes are brilliant.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.