如何分组category
并使用下划线获得平均值?
我有一个对象数组。它应按category
分组,Analytics
的平均值由val
属性计算,即1 + 2 => 3. 3 /类别总数。所以,3/2 => 1.5
预期输出:{ Analytics: 1.5 }
[{
area:"Digital",
category:"Analytics",
qId:"wRHmpHHGzrYLsCEJ3",
type:"Reorganize",
userId:"M4JEJGiPZ8e9om9A",
val:1
},
{
area:"Digital",
category:"Analytics",
qId:"wRHmpHHGzrYLsCEJ3",
type:"Reorganize",
userId:"M4JEJGiPZ8e9om9A",
val:2
}]
由于
答案 0 :(得分:3)
您可以group the objects by category,然后iterate over all the keys in this resulting object和reduce the values:
var types = _.groupBy(array, 'category');
var result = _.mapObject(types, function(val, key) {
return _.reduce(val, function(memo, v) {
return memo + v.val;
}, 0) / val.length;
});
var array = [{
area:"Digital",
category:"Analytics",
qId:"wRHmpHHGzrYLsCEJ3",
type:"Reorganize",
userId:"M4JEJGiPZ8e9om9A",
val:1
},
{
area:"Digital",
category:"Analytics",
qId:"wRHmpHHGzrYLsCEJ3",
type:"Reorganize",
userId:"M4JEJGiPZ8e9om9A",
val:2
}];
var types = _.groupBy(array, 'category');
var result = _.mapObject(types, function(val, key) {
return _.reduce(val, function(memo, v) {
return memo + v.val;
}, 0) / val.length;
});
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;