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

时间:2016-08-21 12:09:15

标签: javascript underscore.js

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

由于

1 个答案:

答案 0 :(得分:3)

您可以group the objects by category,然后iterate over all the keys in this resulting objectreduce 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;
&#13;
&#13;