使用underscorejs获取所有类型的总计数和基于组(类型)的计数
get total count of all types and group(type) based count using underscorejs
我正在尝试获取所有类型的总数和下面json数组的基于组的计数。
var json = {"items":[
{"type":1,"count":10},
{"type":1,"count":10},
{"type":2,"count":20},
{"type":1,"count":30},
{"type":1,"count":40},
{"type":2,"count":100}
]
}
我想得到所有类型的总数(AllTypeTotal:210),以及类型1(TypeOneTotal:90)和类型2(TypeTwoTotal:120)的单独计数。
所以我期待以下数组:
var json = {
"AllTypeTotal":210,
"TypeOneTotal":90,
"TypeTwoTotal":120
}
可以使用Undercore的reduce或原生数组reduce完成。下面是一个下划线解决方案:
var result = _.reduce(json.items, function(memo, item){
// build the correct key
var key = 'Type' + item.type + 'Total';
// update the total
memo.AllTypeTotal += item.count;
// update the type total
memo[key] = (memo[key] | 0) + item.count;
return memo;
}, { AllTypeTotal: 0 } );
我可以帮助您使用lodash,它是下划线的超集,在性能和一致性方面比下划线好得多(请参阅lodash与下划线)。
var uniqTypes = _.pluck(_.uniq(json.items, "type"), "type");
var result = {};
uniqTypes.forEach(function(typeName){
result["type"+typeName+"total"] = 0;
_.map(data.items, function(item){
if(item.type === typeName)
result["type"+typeName+"total"] += item.count;
});
});
相关文章:
- 将单独的数组深层键转换为所需的类型(数组或对象)
- 将大数组(字符串和类型数组的混合物)存储到blob或文件中/从blob或文件检索大数组的最佳方式
- 寻找Javascript类型数组仿真库
- JavaScript 类型数组 - 不同的视图 - 2.
- JavaScript 类型数组 - 不同的视图
- 使用jQuery中的整数字符串类型对数组进行排序
- 将父样式更改应用于组中的所有复选框;全部检查”;运行javascript函数
- 将混合数据类型数组从php传递到javascript数组
- 文档集合(类型数组)在JSDoc中返回值和参数
- 在上传之前预览图像,输入类型为数组文件
- 将32位整数的非类型数组转换为UInt8Array的最有效方法
- 不能在ChromeOS应用程序中正确保存类型数组
- Typescript:无类型数组
- Javascript类型数组vs简单数组:性能
- 将Javascript基本类型数组划分为多个部分
- 使用selectAll获取特定于组的svg元素
- 使用Google位置类型数组
- D3.js:通过 d3 加载平面一维数组.csv导致“类型错误:组数据未定义”/使用 D3.js 加载多个 CSV 文件
- javascript 多维类型数组 (Int8Array) 示例
- JavaScript 类型数组:64 位整数