0

The requirement

What we have-

id          price

1001          200
1001          150
1002          300
1003           50
1002           70
1004           30

What is desired

id            price

1001           350
1002           370
1003           50
1004           30

The above data I have is in an array. Also the order for the output is immaterial. There would be many such records which are repeated or not repeated. So in words the output should be, if any matched found based on id then sum the values of price object and display as a single line item

Below is the array-

arr = [
        {
           'id': '1001',
           'price': 200
        },
        {
          'id': '1001',
          'price': 150
        },
        {
          'id': '1002',
          'price': 300
        },
        ...
        ...
      ]

What I tried -

I tried to loop through the array using two for loops and if for outer loop, inner loop match found find the matches. excerpt-

     for(let i = 0; i < arr.length; i++) {
  for(let j = 1; j < arr.length; j++ ) {
    if(arr[i].id === arr[j].id) {
      if(i != j) {
        console.log("Matched " + i + " with " + j);
      }
    }
  }
}

Now basically from here, I stucked with output. I think the above logic will not work simply because it will loop through all the records everytime. Any help appreciated

1 Answers1

0

Array.prototype.reduce() might help you. reduce() callback takes two arguments, who's first argument is the old/previous iteration value and second argument is the current iteration value/element.

So using this function we can holds our current iteration values to the previous iteration value (total values).

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

const arr = [{'id': '1001','price': 200},{'id': '1001','price': 150},{'id': '1002','price': 300}]
    
const result = Object.values(arr.reduce((acc, cur) => ((acc[cur.id] = acc[cur.id] ? {id: cur.id, price: acc[cur.id].price + (+cur.price)} : cur), acc), {}))
console.log(result)
MH2K9
  • 11,951
  • 7
  • 32
  • 49