-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.

5
  • Array .filter() method. Checkout mdn docs developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 27, 2020 at 18:54
  • 2
    @MFK34, filter is the wrong tool for this. Commented Jul 27, 2020 at 18:55
  • @trincot, Why would using the filter be wrong? Commented Jul 27, 2020 at 21:33
  • @MFK34, because you need information from all objects. Commented Jul 27, 2020 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 Commented Jul 28, 2020 at 3:07

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.