简体   繁体   English

如何在Javascript中将多个项目列表减少为键值对象?

[英]How to reduce a list of multiple items to a key value pair object in Javascript?

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? 什么是最有效的方法呢?

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}

You may be interested in array_count_values from PHPJS. 您可能对array_count_values中的array_count_values感兴趣。 Since the PHP array_count_values function does exactly what you want, it stands to reason that the JavaScript port of that function fits. 由于PHP array_count_values函数完全符合您的要求,因此该函数的JavaScript端口适合。

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): 或者如果你喜欢while循环(有时它们更快,有时候不是):

function toObj(arr) {
  var item, obj = {}, i = arr.length;

  while (i) {
    item = arr[--i];
    obj[item]? ++obj[item] : (obj[item] = 1);
  }

  return obj;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM