I have array of object
const users = [
{ group: 'editor', name: 'Adam', age: 23 },
{ group: 'editor', name: 'John', age: 28 },
{ group: 'editor', name: 'William', age: 34 },
{ group: 'admin', name: 'Oliver', age: 28' }
];
Expected result:
//sum
sumAge = {
editor: 85, // 23+34+28
admin: 28 // 28
}
//average
avgAge = {
editor: 28.33, // (85) / 3
admin: 28 //(28)/1
}
I use reduce() method to group the objects in an array by 'group' and calculate sum:
let sumAge = users.reduce((group, age) => {
group[age.group] = (group[age.group] || 0) + age.age || 1;
return group;
}, {})
console.log('sumAge', sumAge); // sumAge: {editor: 85, admin: 28}
done!
How to group object of Array by key 'group' and calculate average?. I tried:
let ageAvg= users.reduce((group, age) => {
if (!group[age.group]) {
group[age.group] = { ...age, count: 1 }
return group;
}
group[age.group].age+= age.age;
group[age.group].count += 1;
return group;
}, {})
const result = Object.keys(ageAvg).map(function(x){
const item = ageAvg[x];
return {
group: item.group,
ageAvg: item.age/item.count,
}
})
console.log('result',result);
/*
result=[
{group: "editor", ageAvg: 28.33}
{group: "admin", ageAvg: 28}
]
But Expected result:
result = {
editor: 28.33, // (85) / 3
admin: 28 //(28)/1
}
map()will not work for you. And if you want justgroup: average, then your return inside that map doesn't match that at allreduce()the result of that map to the single object you want