How to group by, calculate sum and get average in JavaScript array?(如何在 JavaScript 数组中分组、计算总和并获取平均值?)
问题描述
我有一个对象数组
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' }
];
预期结果:
//sum
sumAge = {
editor: 57, // 23+34
admin: 56 // 28+28
}
//average
avgAge = {
editor: 28.5, // (23+34) / 2
admin: 28 //(28+28)/2
}
我使用 reduce()
方法将数组中的对象按组"分组并计算总和:
I use reduce()
method to group the objects in an array by 'group' and calulate 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: 57, admin: 56}
done!
如何通过键组"对数组的对象进行分组并计算平均值?.我试过了:
How to group object of Array by key 'group' and calulate 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.5}
{group: "admin", ageAvg: 28}
]
但预期结果:
result = {
editor: 28.5, // (23+34) / 2
admin: 28 //(28+28)/2
}
推荐答案
您可以简单地使用 reduce
来获取 age groups
的 total
.
You could simply use reduce
to get the total
of age groups
.
并使用 object.keys
length 从 getAvg
函数中获取作为新对象的总数的平均值.
And use object.keys
length to get the average of your total as new object from getAvg
function.
演示:
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}
这篇关于如何在 JavaScript 数组中分组、计算总和并获取平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 JavaScript 数组中分组、计算总和并获取平
基础教程推荐
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01