count category by userID using Underscorejs

China☆狼群 提交于 2019-12-08 10:52:47

问题


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:


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);


来源:https://stackoverflow.com/questions/39273546/count-category-by-userid-using-underscorejs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!