Frequency-based array sorting in Ruby on Rails

I have a nested array of numbers, arranged as follows:

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

I only need one array with all the keys inside, without repetition, so I used this:

 ids = ids.flatten.uniq 

This creates the following:

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

Since I used .uniq , it eliminates duplicate values. However, I would like to order values โ€‹โ€‹depending on how often they appear in sub-arrays, and not depending on what order they are in - here is something like this:

 ids = [8,10,7,5,25,15,30,32] 
+6
source share
4 answers

This should do:

 ids.flatten.group_by {|i| i}.sort_by {|_, a| -a.count}.map &:first 
+7
source
 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] 
+3
source

Slow but understandable (hopefully) person new to Ruby:

 flattened_ids = ids.flatten unique_ids = flattened_ids.uniq sorted_ids = unique_ids.sort_by { |e| -flattened_ids.count(e) } 
+3
source

This may not be the best solution, but:

 ids.flatten.each_with_object(Hash.new(0)) { |id, count| count[id] += 1 }.sort_by { |a| -a[1] }.map(&:first) 
0
source

Source: https://habr.com/ru/post/985278/


All Articles