-1

I have an array with the following objects:

public names: Array<any> = [
 {name: 'John', car:'BMW',  value1: 500, value2: 350},
 {name: 'John', car:'AUDI',  value1: 500, value2: 350},
 {name: 'John', car:'AUDI',  value1: 250, value2: 200},
 {name: 'Paul', car: 'AUDI',  value1: 290, value2: 200},
 {name: 'John', car:'BMW',  value1: 600, value2: 360},
 {name: 'John', car:'BMW',  value1: 500, value2: 350},
 {name: 'Paul', car: 'AUDI',  value1: 120, value2: 50},
 {name: 'John', car:'BMW',  value1: 100, value2: 100},
];

I would like to merge them passing the common name and car as a reference and do the sum of value1 and value2 according to the result below. I tried to use reduce but I think I'm wrong in the type.

Expected result:

[
 {name: 'John', car:'BMW', value1: 1700, value2: 1160},
 {name: 'John', car:'AUDI', value1: 750, value2: 550},
 {name: 'Paul', car: 'AUDI', value1: 410, value2: 250}
]

I tried to do by reduce but I think I got the type wrong.

Kalla
  • 7
  • 2

1 Answers1

0

look at the answer in this question How to get distinct values from an array of objects in JavaScript?

with this you can get the distinct list of objects. After that iterate over all your objects and increment the value props on the elements where your two key properties fit

Platinium
  • 33
  • 7
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 14 '22 at 15:15