在Javascript中使用arr.reduce()和一个用作hashmap的对象

时间:2014-05-02 07:49:20

标签: javascript object map hashmap reduce

我有一系列卡片,如此:["两个","国王","九","两个&#34 ;,...] 我正在尝试构建一个哈希映射,计算每个排名在数组中出现的次数,因此对于上面的输入,它应该输出:{" two":2," nine": 1,"国王":1}

我想使用arr.reduce()函数,这是我到目前为止所尝试的:

  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
  });

运行时,Chrome会告诉我count_obj是"两个"那个等级是"两个"。这让我相信count_obj不会被视为一个hashmap,这被证明是正确的,因为chrome也会抛出错误"不能使用''运营商搜索' Two'在Two"中,所以我需要以某种方式让JS将count_obj视为一个hashmap。

任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

这就是你想要的:

function count(xs) {
  return xs.reduce(function(a,e) {
    return a[e] = ++a[e]||1, a;
  },{});
}

示例:

var xs = ["two", "king", "nine", "two"];
console.log(count(xs));
//^ {king:1, nine:1, two:2}