Get top n elements from ruby array of hash values
arrays, ruby, sorting
Solution
`Enumerable#group_by` to the rescue (as usual):
result.group_by { |r| r["count"] }
.sort_by { |k, v| -k }
.first(2)
.map(&:last)
.flatten
Most of the work is done by the `group_by`. The `sort_by` simply lines things up so that `first(2)` will pick off the groups you want. Then `map` with `last` will extract the count/name hashes that you started with and the final `flatten` will clean up the extra left over arrays.
Problem
Hey I have an array where each element is a hash containing a few values and a count. ``` result = [ {"count" => 3,"name" => "user1"}, {"count" => 10,"name" => "user2"}, {"count" => 10, "user3"}, {"count" => 2, "user4"} ] ``` I can sort the array by count as follows: ``` result = result.sort_by do |r| r["count"] end ``` Now I want to be able to retrieve the top n entries based on count (not just first(n)) Is there an elegant way to do this? So as an example, let n = 1 I would expect a result set of. ``` [{"count" => 10,"name" => "user2"}, {"count" => 10, "user3"}] ``` since I asked for all entries with the highest score.. if I asked for top 2 highest scores I'd get ``` [{"count" => 10,"name" => "user2"}, {"count" => 10, "user3"}, {"count" => 3, "user1"}] ```