I have an array of hashed in Ruby that looks like this:
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"}
]
Edit::
So if it's returned in this format (from 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"}]
}
How can I apply the same process. i.e. Get to the Item embedded within the array?
Using Ruby I can interate over the array and remove the duplicate values like this:
counted = Hash.new(0)
domains.each { |h| counted[h["country"]] += 1 }
counted = Hash[counted.map {|k,v| [k,v.to_s] }]
Which output something like this:
{"Germany"=>"3",
"United Kingdom"=>"2",
"Hungary"=>"3",
"United States"=>"3",
"France"=>"1",
"Slovakia"=>"1",
"Norway"=>"2"}
My question is what is the best way to achieve the same using Javascript possibly using a library like underscore?
Best Regards,
Carlskii
Just loop over the values and increment a count in a hash.
var count = {};
domains.forEach(function (obj) {
var c = obj.country;
count[c] = count[c] ? count[c] + 1 : 1;
});
(Note that IE 8 and earlier don't support forEach
, use a polyfill or a regular for loop if you care about them)
You can also use the reduce function much like in Ruby:
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;
}, {});