Search code examples
arraysrubyhashunique-key

Array of hashes, how to count the list of 'webpages' with most unique 'page' views?


I am trying to display the most unique page views in order, but am unsure how. i have the variable with data:

data = [{"help_page/1"=>"126.318.035.038"},
 {"contact"=>"184.123.665.067"},
 {"home"=>"184.123.665.067"},
 {"about/2"=>"444.701.448.104"},
 {"help_page/1"=>"929.398.951.889"},
 {"index"=>"444.701.448.104"},
 {"help_page/1"=>"722.247.931.582"},
 {"about"=>"061.945.150.735"},
 {"help_page/1"=>"646.865.545.408"},
 {"home"=>"235.313.352.950"},
 {"help_page/1"=>"543.910.244.929"},
 {"home"=>"316.433.849.805"},
 {"contact"=>"543.910.244.929"}]

i tried something like this:

data.sort_by {|k, v| -v.uniq.count}.collect{|k, v| "#{k}\t#{v.uniq.count} #{'unique views', v.uniq.count}"}

i am trying to get results somewhat similar to the below:

/help_page/1    XX unique views
/contact    XX unique views
/home   XX unique views
/index  XX unique views
/about/2    XX unique views
/about  XX unique views

but no success.


Solution

  • Enumerable#group_by is your friend, everything else below is just formatting the output.

    data.group_by do |h|
      h.to_a.first.first
    end.map do |k, v|
      [k, v.count]
    end.sort_by(&:last).reverse.to_h
    #⇒ {"help_page/1"=>5,
    #   "home"=>3,
    #   "contact"=>2,
    #   "about"=>1,
    #   "index"=>1,
    #   "about/2"=>1}