问题
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