count category by userID using Underscorejs

2019-06-14 02:41发布

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

1条回答
走好不送
2楼-- · 2019-06-14 03:22

Your example makes no sense, but I suspect your data is wrong. Here is some example code. I have added user 3 which represents the data to provide the expected answer in your question.

var 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
},{
  area:"Digital",
  category:"Technology",
  userId:3,
  weightedAverage:30
},{
  area:"Digital",
  category:"Analytics",
  userId:3,
  weightedAverage:30
}];


function printCategoriesByUserId(userId) {
  var cats = _.where(arrayFlatten, {userId: userId});
  var types = _.groupBy(cats, 'category');

  _.each(types, function(val, key) {
    console.log(key + ": " + val.length);
  });
}

// prints Techology: 2
printCategoriesByUserId(1);

// prints Analytics: 1
printCategoriesByUserId(2);

// prints Technology: 1, Analytics: 1
printCategoriesByUserId(3);
查看更多
登录 后发表回答