如何使用 underscorejs 分组并获得平均值

How to groupby and get average using underscorejs

如何分组 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
}]

谢谢

你可以group the objects by category, then iterate over all the keys in this resulting object and 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>