Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  158] [ 3]  / answers: 1 / hits: 59962  / 12 Years ago, sat, october 13, 2012, 12:00:00

Possible Duplicate:

array_count_values for javascript instead






Let's say I have simple JavaScript array like the following:



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


I want to group and count of each so I would expect a key/value map of:



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

More From » arrays

 Answers
7
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;
}, {} );

[#82571] Thursday, October 11, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;