I have array of object
const users = [
{ group: \'editor\', name: \'Adam\', age: 23 },
{ group: \'admin\', n
You could simply use reduce
to get the total
of age groups
.
And use object.keys
length to get the average of your total as new object from getAvg
function.
Demo:
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
}
];
const sumId = users.reduce((a, {
group,
age
}) => (a[group] = (a[group] || 0) + age, a), {});
console.log(sumId); //{editor: 57, admin: 56}
//Average
const getAvg = (x) => {
const item = {}
const count = Object.keys(x).length
Object.keys(x).map(function(y) {
item[y] = sumId[y] / count
})
return item
}
console.log(getAvg(sumId)); //{editor: 28.5, admin: 28}