const data = [
{ name: 'Sasha', apple: 8, banana: 6, cherry: 9 },
{ name: 'Artur', apple: 4, banana: 2, cherry: 1 },
{ name: 'Sasha', apple: 5, banana: 7, cherry: 3 },
{ name: 'Bogdan', apple: 6, banana: 11, cherry: 8 },
{ name: 'Artur', apple: 8, banana: 6, cherry: 9 },
];
const collectBy = (collection, property) =>
collection.reduce((accumulator, entry) => {
const { [property]: key, ...data } = entry;
if (!accumulator.hasOwnProperty(key)) {
accumulator[key] = data;
} else {
for (const [property, value] of Object.entries(data)) {
accumulator[key][property] += value;
}
}
return accumulator;
}, {});
const collectedData = collectBy(data, 'name');
console.log(collectedData);
/*
{
Sasha: { apple: 13, banana: 13, cherry: 12 },
Artur: { apple: 12, banana: 8, cherry: 10 },
Bogdan: { apple: 6, banana: 11, cherry: 8 }
}
*/