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]
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]
This should do:
ids.flatten.group_by {|i| i}.sort_by {|_, a| -a.count}.map &:first
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With