在JavaScript / NodeJS / Underscore中计算哈希值

时间:2012-10-06 09:26:48

标签: javascript ruby node.js underscore.js

我在Ruby中有一个哈希数组,如下所示:

domains = [
 { "country" => "Germany"},
 {"country" => "United Kingdom"},
 {"country" => "Hungary"},
 {"country" => "United States"},
 {"country" => "France"},
 {"country" => "Germany"},
 {"country" => "Slovakia"},
 {"country" => "Hungary"},
 {"country" => "United States"},
 {"country" => "Norway"},
 {"country" => "Germany"},
 {"country" => "United Kingdom"},
 {"country" => "Hungary"},
 {"country" => "United States"},
 {"country" => "Norway"}
]

编辑::

所以,如果它以这种格式(来自CouchDB)返回:

domains= {"total_rows":55717,"offset":0,"rows": [
    {"country":"Germany"},  
    {"country":"United Kingdom"},
    {"country":"Hungary"},
    {"country":"United States"},\   \ 
    {"country":"France"},
    {"country":"Germany"},
    {"country":"Slovakia"},
    {"country":"Hungary"},
    {"country":"United States"},
    {"country":"Norway"},
    {"country":"Germany"}, 
    {"country":"United Kingdom"},
    {"country":"Hungary"}, 
    {"country":"United States"},
    {"country":"Norway"}]
}

如何应用相同的流程。即到达数组中嵌入的项目?

使用Ruby我可以对数组进行交互并删除重复的值,如下所示:

counted = Hash.new(0)
domains.each { |h| counted[h["country"]] += 1 }
counted = Hash[counted.map {|k,v| [k,v.to_s] }]

这样的输出是这样的:

{"Germany"=>"3",
 "United Kingdom"=>"2",
 "Hungary"=>"3",
 "United States"=>"3",
 "France"=>"1",
 "Slovakia"=>"1",
 "Norway"=>"2"}

我的问题是使用Javascript可能使用类似下划线的库来实现相同的最佳方法是什么?

最诚挚的问候,

Carlskii

2 个答案:

答案 0 :(得分:1)

只需循环遍历值并增加哈希中的计数。

var count = {};
domains.forEach(function (obj) { 
    var c = obj.country;
    count[c] = count[c] ? count[c] + 1 : 1;
});

(请注意,IE 8及更早版本不支持forEach,如果您关心它们,请使用polyfill或常规for循环)

答案 1 :(得分:0)

您也可以像使用Ruby一样使用reduce函数:

domains.reduce(function(country_with_count, country_object) {
    country_with_count[country_object['country']] = (country_with_count[country_object['country']] || 0) + 1;
    return country_with_count;
}, {});