我正在寻找一种有效的方法来计算元素的出现次数。 我循环读取数据,在每一步中我都想增加结果数组中正确的对象元素,或者创建一个新的对象元素(如果尚不可用)。
我必须处理大量数据,因此我需要一个快速的解决方案。这是一个工作版本:
var hugeDataObject = [
{id: '1234', dark: true},
{id: '5678', dark: true},
{id: '91011', dark: true},
{id: '91011', dark: false}
];
var ids = [];
var darks = [];
var allIds = [];
var allDarks = [];
hugeDataObject.forEach(function(attrs) {
var index = allIds.indexOf(attrs.id);
if(index >= 0) ids[index].amount += 1;
else {
ids.push({type: attrs.id, amount: 1});
allIds.push(attrs.id);
}
var index = allDarks.indexOf(attrs.dark);
if(index >= 0) darks[index].amount += 1;
else {
darks.push({type: attrs.dark, amount: 1});
allDarks.push(attrs.dark);
}
});
Fiddle 但我的类型比较多,需要统计的类型较多,所以变量太多了。
结果:
ids = [
{type: '1234', amount: 1},
{type: '5678', amount: 1},
{type: '91011', amount: 2}
]
darks = [
{type: true, amount: 3},
{type: false, amount: 1}
]
(如果你使用loDash,就可以了)
提前致谢!
最佳答案
如何使用更简单的结构来存储:
var objects = {};
objects['id1234'] = 384;
objects['id5678'] = 955;
objects['id91011'] = 1510;
/* increment */
objects['id1234']++;
关于javascript - 将出现的次数存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25075254/