Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting arrays based on frequency in Ruby on Rails

I have a nested array of numbers, arranged like this:

ids = [[5,8,10],[8,7,25],[15,30,32],[10,8,7]]

I only need a single array with all of the keys inside, without repeating, so I used this:

ids = ids.flatten.uniq

That produces this:

ids = [5,8,10,7,25,15,30,32]

Since I used .uniq, it eliminates the duplicate values. However, I'd like to order the values based on how often they appear in the sub-arrays, rather than whichever order they happen to be in -- so something like this:

ids = [8,10,7,5,25,15,30,32]
like image 557
fr3d0 Avatar asked Apr 16 '15 15:04

fr3d0


2 Answers

ids_flatten = [[5,8,10],[8,7,25],[15,30,32],[10,8,7]].flatten
ids_hist = ids_flatten.group_by{ |v| v }.map{ |k, v| [k, v.size] }
soreted_ids_hist = ids_hist.sort_by{|x| -x[1]}

soreted_ids_hist.map(&:first)
 => [8, 7, 10, 25, 5, 15, 30, 32]
like image 43
Saurabh Avatar answered Nov 04 '22 20:11

Saurabh


This should do:

ids.flatten.group_by {|i| i}.sort_by {|_, a| -a.count}.map &:first
like image 117
BroiSatse Avatar answered Nov 04 '22 21:11

BroiSatse