This is what you want:
function count(xs) {
return xs.reduce(function(a,e) {
return a[e] = ++a[e]||1, a;
},{});
}
Example:
var xs = ["two", "king", "nine", "two"];
console.log(count(xs));
//^ {king:1, nine:1, two:2}
Pregunta
I have an array of ranks of cards, as such: ["two", "king", "nine", "two", ...] I am trying to build a hash map that counts how many times each rank appears in the array, so for the above input it should output: {"two": 2, "nine": 1, "king": 1}
I want to use the arr.reduce() function, and this is what I have tried so far:
var counts = ranks.reduce(function (count_obj, rank){
console.log("count_obj is " + count_obj); //Outputs "Two"
console.log("rank is " + rank); //Outputs "Two"
if (rank in count_obj){ //If the rank is already in the hashmap, increment its value
count_obj[rank]++;
}
else count_obj[rank] = 1; //If the rank isn't already in the hashmap, create it and mark it's value as 1
});
When running this, Chrome tells me that count_obj is "Two" and that rank is "Two". This leads me to believe that count_obj is not being treated as a hashmap, and this is proved correct as chrome also throws the error "Cannot use 'in' operator to search for 'Two' in Two", so I need to somehow make JS treat count_obj as a hashmap.
Any help appreciated.
Solución
This is what you want:
function count(xs) {
return xs.reduce(function(a,e) {
return a[e] = ++a[e]||1, a;
},{});
}
Example:
var xs = ["two", "king", "nine", "two"];
console.log(count(xs));
//^ {king:1, nine:1, two:2}