I have a problem trying to sum values when they are within an object.
Given the following array:
const data = [
{
id: "tom",
values: { ten: 10, twenty: 20, thirty: 30 },
},
{
id: "tom",
values: { ten: 10, twenty: 20, thirty: 30 },
},
{
id: "dick",
values: { ten: 10, twenty: 20, thirty: 30 },
},
{
id: "harry",
values: { ten: 10, twenty: 20, thirty: 30 },
},
{
id: "harry",
values: { ten: 10, twenty: 20, thirty: 30 },
},
];
I need to sum each of the numbers in the values object where the id matches, giving the following result:
const result = [
{
id: "tom",
values: { ten: 20, twenty: 40, thirty: 60 },
},
{
id: "dick",
values: { ten: 10, twenty: 20, thirty: 30 },
},
{
id: "harry",
values: { ten: 20, twenty: 40, thirty: 60 },
}
];
Is there an easy way to achieve this?
Maybe some combination of reduce and map?