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 }
}
*/
// исходный массив
const arr = [
{ 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 result = arr.reduce((acc, current) => {
// если текущее имя есть в свойствах объекта
if (acc.hasOwnProperty(current.name)) {
// извлекаем свойства
const { apple, banana, cherry } = current;
// суммируем количество
acc[current.name].apple += apple;
acc[current.name].banana += banana;
acc[current.name].cherry += cherry;
} else {
// иначе добавляем новое имя в объект и копируем свойства
const { apple, banana, cherry } = current;
acc[current.name] = {
apple,
banana,
cherry
};
}
return acc;
},
{} // начальное значение
);
console.log(result);
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 },
];
data.reduce((acc, item) => {
const { name, ...rest } = item;
if (!acc.hasOwnProperty(name)) acc[name] = { ...rest };
else {
const keys = Object.keys(rest);
keys.forEach(key => acc[name][key] += rest[key])
}
return acc
}, {})
let arr =[
{ 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 }
]
arr = arr.map(e=>e.name).filter((value,index,self)=> self.indexOf(value) === index).map(e=>{
res = {name:e};
arr.filter(e1=>e1.name == e).forEach(v=>{
for(let key in v)
if(key != "name")
res[key] = (res[key] || 0) + v[key];
});
return res;
})
console.log(arr);