使用 Underscorejs 按用户 ID 计算类别 [英] count category by userID using Underscorejs

查看:18
本文介绍了使用 Underscorejs 按用户 ID 计算类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 undersocrejs 基于 userId 的计数类别.

Countby category based on userId using undersocrejs.

请参考下面的脚本,它打印值Technology:2"&分析:1".

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

预期答案:技术:1"&"Analytics:1" 因为两个技术"对象都是相同的用户 ID,即.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);

谢谢

推荐答案

你的例子没有意义,但我怀疑你的数据是错误的.这是一些示例代码.我添加了代表数据的用户 3,以在您的问题中提供预期的答案.

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

这篇关于使用 Underscorejs 按用户 ID 计算类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆