1

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?

3
  • 1
    Where do you pull the number from? Commented Jul 10, 2012 at 1:18
  • yea, depending on what the number is for we would suggest different things Commented Jul 10, 2012 at 1:19
  • Apologies. The value is the number of occurrences of each state. Edited to clarify. Commented Jul 10, 2012 at 1:22

3 Answers 3

4
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}
Sign up to request clarification or add additional context in comments.

2 Comments

I would put a comment next to the |= as it is as elegant as it is confusing at first glance (possibly second glance to someone less versed in such things).
Please don't use for..in iteration with arrays unless you account for inherited properties and other quirks.
0

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.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.