Underscorejs - Countby category


#1

Countby category based on userId using undersocrejs.

Please refer the below script, its printing the value “Technology:2” & “Analytics:1”.

Expected answer: “Technology:1” & “Analytics:1” because both the ‘Technology’ objects are the same userId ie. 1

arrayFlatten = [
{
area:“Digital”,
category:“Technology”,
userId:1,
weightedAverage:10
},
{
area:“Digital”,
category:“Technology”,
userId:1,
weightedAverage:20
},
{
area:“Digital”,
category:“Analytics”,
userId:2,
weightedAverage:30
}
]
var types = _.groupBy(arrayFlatten, ‘category’);
console.log(types);
var result = {};
_.each(types, function(val, key) {
console.log(key+" "+val.length);
});
console.log(result);
Thanks


#2

@vikramappdev, try using this code

_.each(types, function(val, key) {
  users = _.pluck(val, 'userId')
  console.log(key+" "+ _.uniq(users).length);
}); 

The pluck function will get all the user ids defined inside that category and the uniq will make you only count them once.