-1

I want to reduce an array where the items with the same id have one of their properties summed.

The array would look like this

array = [
{
  id: 123,
  qty: 10,
  unit: 'dollar'
},
{
  id: 456,
  qty: 15,
  unit: 'euro'
},
{
  id: 123,
  qty: 20,
  unit: 'dollar'
}]

With the result being an array that looks like this

array = [
{
  id: 123,
  qty: 30,
  unit: 'dollar'
},
{
  id: 456,
  qty: 15,
  unit: 'euro'
}]

I've been trying to do this with reduce but to no avail.

  • Array .filter() method. Checkout mdn docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – MFK34 Jul 27 '20 at 18:54
  • 2
    @MFK34, filter is the wrong tool for this. – trincot Jul 27 '20 at 18:55
  • @trincot, Why would using the filter be wrong? – MFK34 Jul 27 '20 at 21:33
  • @MFK34, because you need information from *all* objects. – trincot Jul 27 '20 at 21:36
  • @tincot, oh ok, can u give me an example of where .filter be best used or where it is recommended to use. I just trying to understand why vs why not filter. If you have any docs / links that explain the recommend way to use the various array methods. Thanks – MFK34 Jul 28 '20 at 03:07

1 Answers1

0

Here is the simple approach using for loop and .find method of an array.

var array = [
{
  id: 123,
  qty: 10,
  unit: 'dollar'
},
{
  id: 456,
  qty: 15,
  unit: 'euro'
},
{
  id: 123,
  qty: 20,
  unit: 'dollar'
}];

var res = [];
for(let i=0;i<array.length;i++){
  let tempObj = res.find(obj => obj.id===array[i].id);
  if(tempObj){
    tempObj.qty+=array[i].qty;
  } else {
    res.push(array[i]);
  }
}

console.log(res);
Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26