How to work out frequency of certain key's value in an array of hashes?
I have an array of hashes. Each hash has an uses
key. Multiple hashes can share the same uses
value.
[{uses => 0},{uses开发者_C百科 => 1},{uses => 2},{uses => 1},{uses => 0},{uses => 1},{uses => 3}]
How can I generate an array of the most frequent uses
values, in a descending order?
[1,0,2,3]
Referencing this discussion of frequency of items in a list, we can easily modify this for your task.
> unsorted = [{:uses=>0}, {:uses=>1}, {:uses=>2}, {:uses=>1}, {:uses=>0}, {:uses=>1}, {:uses=>3}].map{|h| h[:uses]}
> sorted = unsorted.uniq.sort_by{|u| unsorted.grep(u).size}.reverse
=> [1, 0, 2, 3]
hs.inject({}) do |histogram, h|
histogram.merge(h[:uses] => (histogram[h[:uses]] || 0) + 1)
end.sort_by { |k, v| -v }.map { |k, v| k }
# => [1, 0, 2, 3]
I always recommend to use Facets, though:
http://rubyworks.github.com/facets/doc/api/core/Enumerable.html
hs.frequency.sort_by { |k, v| -v }.map { |k, v| k }
# => [1, 0, 2, 3]
Here is a one pass solution:
a = [{:uses => 0},{:uses => 1},{:uses => 2},{:uses => 1},{:uses => 0},
{:uses => 1},{:uses => 3}]
# A hash with the frequency count is formed in one iteration of the array
# followed by the reverse sort and extraction
a.inject(Hash.new(0)) { |h, v| h[v[:uses]] += 1;h}.
sort{|x, y| x <=> y}.map{|kv| kv[0]}
精彩评论