Reputation: 3946
I have an array of states:
['CO','CA','CO','AL', ... ,'NV']
and I'd like to reduce to:
{ 'CO': 9, 'CA':17, 'AL':1, etc}
The value is the number of times each state occurs in the array.
what's the most efficient way to do this?
Upvotes: 1
Views: 82
Reputation: 6839
function compress2dict( raw_arr )
{
var ret={};
for(var i=0;i<raw_arr.length;i++)
{
var item=raw_arr[i];
ret[item]|=0;
ret[item]++;
}
return ret;
}
a = ['CO','BO','CO','CC','CC','CO','CC']
b = compress2dict(a)
b
{'BO':1, 'CC':3, 'CO':3}
Upvotes: 4
Reputation: 147363
I expect you just iterate over the array, assign the member values to object property names and the number of occurences as the value:
function toObj(arr) {
var item, obj = {};
for (var i=0, iLen=arr.length; i<iLen; i++) {
item = arr[i];
obj[item]? ++obj[item] : (obj[item] = 1);
}
return obj;
}
Or if you like while loops (sometimes they're faster, sometimes not):
function toObj(arr) {
var item, obj = {}, i = arr.length;
while (i) {
item = arr[--i];
obj[item]? ++obj[item] : (obj[item] = 1);
}
return obj;
}
Upvotes: 0
Reputation: 324620
You may be interested in array_count_values
from PHPJS. Since the PHP array_count_values
function does exactly what you want, it stands to reason that the JavaScript port of that function fits.
Upvotes: 0