I've tried to use a few different options from filter, reduce and includes but can't wrap my head round how to do this.
I have this array below of objects:
[
{ name: 'GrapeCo', weight: 0.15 },
{ name: 'MicroFit', weight: 0.5 },
{ name: 'GreenCo', weight: 0.3 },
{ name: 'GrapeCo', weight: 0.2 },
{ name: 'GrapeCo', weight: 0.3 },
{ name: 'GoldenGadgets', weight: 0.3 },
{ name: 'SpaceY', weight: 0.3 },
{ name: 'BeanzRUS', weight: 0.6 },
{ name: 'GrapeCo', weight: 0.2 },
{ name: 'SolarCorp', weight: 0.8 }
]
And I would like to find all of the duplicate named companies and merge them into one with the total weight.
So the output would be something like this:
[
{ name: 'MicroFit', weight: 0.5 },
{ name: 'GreenCo', weight: 0.3 },
{ name: 'GoldenGadgets', weight: 0.3 },
{ name: 'SpaceY', weight: 0.3 },
{ name: 'BeanzRUS', weight: 0.6 },
{ name: 'GrapeCo', weight: 0.85 },
{ name: 'SolarCorp', weight: 0.8 }
]
My reduce method that I have been trying to get to work looks like this below:
companies.reduce(
(acc, elem) => {
return {
...acc,
[elem.name]: elem.weight + (acc[name] || 0),
};
},
{}
);