如何使用underscorejs分组并获得平均值 [英] How to groupby and get average using underscorejs
本文介绍了如何使用underscorejs分组并获得平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何按category
分组并使用下划线求平均值?
How to groupBy category
and get the average using underscore?
我有一个对象数组.它应该按 category
分组,Analytics
的平均值是根据 val
属性计算的,即 1+2 => 3. 3/total类别的数量.所以,3/2 => 1.5
I have an array of objects. It should be grouped by category
and average for Analytics
is calculated from the val
property ie., 1+2 => 3. 3/total number of categories. So, 3/2 => 1.5
预期输出:{ 分析: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
}]
谢谢
推荐答案
您可以按类别对对象进行分组,然后遍历这个结果对象中的所有键和减少值:
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>
这篇关于如何使用underscorejs分组并获得平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文