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