I have an array of objects
const users = [
{ group: 'editor', name: 'Adam', age: 23 },
{ group: 'admin', name: 'John', age: 28 },
{ group: 'editor', name: 'William', age: 34 },
{ group: 'admin', name: 'Oliver', age: 28' }
];
The desired outcome is:
//sum
sumAge = {
editor: 57, // 23+34
admin: 56 // 28+28
}
//average
avgAge = {
editor: 28.5, // (23+34) / 2
admin: 28 //(28+28)/2
}
To achieve this, I utilized the reduce()
method to group objects in the array by 'group' and calculate the total age:
let sumAge = users.reduce((group, age) => {
group[age.group] = (group[age.group] || 0) + age.age || 1;
return group;
}, {})
console.log('sumAge', sumAge); // sumAge: {editor: 57, admin: 56}
done!
How can we group objects of the array by the key 'group' and calculate the average age? I attempted:
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.5}
{group: "admin", ageAvg: 28}
]
However, the expected outcome is:
result = {
editor: 28.5, // (23+34) / 2
admin: 28 //(28+28)/2
}