I'm looking for an effective way to count the occurrence of elements. I read the data in a loop, and in every step I want to increase the right object element in the result array, or create a new one, if it isn't available yet.
I have to work with a lot of data, so I need a quick solution. Here is a working version:
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 But I have more types, what I need to count, so there is too much variable.
The result:
ids = [
{type: '1234', amount: 1},
{type: '5678', amount: 1},
{type: '91011', amount: 2}
]
darks = [
{type: true, amount: 3},
{type: false, amount: 1}
]
(If you use loDash, it's ok)
Thanks in advance!