JavaScript Group By Array

前端 未结 2 1037
暖寄归人
暖寄归人 2020-12-01 09:30

Possible Duplicate:
array_count_values for javascript instead

Let\'s say I have simple JavaScript array like

相关标签:
2条回答
  • 2020-12-01 09:41
    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);
    

    results in

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

    This works, too:

    hist = arr.reduce( function (prev, item) { 
      if ( item in prev ) prev[item] ++; 
      else prev[item] = 1; 
      return prev; 
    }, {} );
    
    0 讨论(0)
  • 2020-12-01 09:47

    You can loop through each index and save it in a dictionary and increment it when every that key is found.

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

    Output will be:

    Boat: 1
    Car: 2
    Truck: 2
    
    0 讨论(0)
提交回复
热议问题