JavaScript的组由array [复制](JavaScript Group By Array

2019-06-18 12:40发布

可能重复:
array_count_values的JavaScript,而不是

比方说,我有简单的JavaScript数组如下所示:

var array = ['Car', 'Car', 'Truck', 'Boat', 'Truck'];

我想每个组数,所以我期望的键/值映射:

{
  Car   : 2,
  Truck : 2,
  Boat  : 1
}

Answer 1:

var arr = [ 'Car', 'Car', 'Truck', 'Boat', 'Truck' ];
var hist = {};
arr.map( function (a) { if (a in hist) hist[a] ++; else hist[a] = 1; } );
console.log(hist);

结果是

{ Car: 2, Truck: 2, Boat: 1 }

这工作,太:

hist = arr.reduce( function (prev, item) { 
  if ( item in prev ) prev[item] ++; 
  else prev[item] = 1; 
  return prev; 
}, {} );


Answer 2:

你可以通过各指标环,并将其保存在一本字典,并增加它时,每一个键被找到。

count = {};
for(a in array){
  if(count[array[a]])count[array[a]]++;
  else count[array[a]]=1;
}

输出将是:

Boat: 1
Car: 2
Truck: 2


文章来源: JavaScript Group By Array [duplicate]