How to groupby and get average using underscorejs

2019-07-15 02:18发布

问题:

How to groupBy category and get the average using underscore?

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

Expected Output: { 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
}]

Thanks

回答1:

You can 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>