使用Underscorejs按用户ID计算类别

时间:2016-09-01 13:59:00

标签: underscore.js

使用undersocrejs基于userId的Countby类别。

请参考以下脚本,其打印值"技术:2" &安培; "分析:1"

预期答案:"技术:1" &安培; "分析:1"因为这两项技术都是'对象是相同的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);

由于

1 个答案:

答案 0 :(得分:0)

您的示例毫无意义,但我怀疑您的数据是错误的。这是一些示例代码。我添加了用户3,它代表了数据,以便在您的问题中提供预期的答案。

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