汇总对象数组并计算每个唯一对象名称的平均值 [英] Summarize array of objects and calculate average value for each unique object name
本文介绍了汇总对象数组并计算每个唯一对象名称的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数组:
var array = [
{
name: "a",
value: 1
},
{
name: "a",
value: 2
},
{
name: "a",
value: 3
},
{
name: "b",
value: 0
},
{
name: "b",
value: 1
}
];
我需要一个这样的数组:
And I need an array like this:
var newarray = [
{
name: "a",
value: 2
},
{
name: "b",
value: 0.5
}
]
其中新数组将每个唯一名称作为具有平均值的对象.
Where the new array has each unique name as an object with the average value.
有没有一种简单的方法可以做到这一点?
Is there an easy way to accomplish this?
推荐答案
您必须遍历数组,计算每个对象的总和和计数.这是一个快速实现:
You'll have to loop through the array, computing the sum and counts for each object. Here's a quick implementation:
function average(arr) {
var sums = {}, counts = {}, results = [], name;
for (var i = 0; i < arr.length; i++) {
name = arr[i].name;
if (!(name in sums)) {
sums[name] = 0;
counts[name] = 0;
}
sums[name] += arr[i].value;
counts[name]++;
}
for(name in sums) {
results.push({ name: name, value: sums[name] / counts[name] });
}
return results;
}
请注意,如果您使用像 Underscore.js 这样的库,这种事情会变得更容易::>
Note, this kind of thing can be made much easier if you use a library like Underscore.js:
var averages = _.chain(array)
.groupBy('name')
.map(function(g, k) {
return {
name: k,
value: _.chain(g)
.pluck('value')
.reduce(function(x, y) { return x + y })
.value() / g.length
};
})
.value();
这篇关于汇总对象数组并计算每个唯一对象名称的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文