Vikram Sethumadhavan Vikram Sethumadhavan - 3 months ago 15
Javascript Question

How to groupby and get average using underscorejs

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

Answer

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>