总结对象的数组,每个唯一对象名称计算平均值 [英] Summarize array of objects and calculate average value for each unique object name
本文介绍了总结对象的数组,每个唯一对象名称计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,像这样:
I have an array like so:
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屋!
查看全文