6

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]
0

4 Answers 4

7

This should do:

ids.flatten.group_by {|i| i}.sort_by {|_, a| -a.count}.map &:first
Sign up to request clarification or add additional context in comments.

9 Comments

@QPaysTaxes - Try running the command above step by step to see what is going on. Is there any particular element you are not sure about?
i tried it but it says there's a syntax error in there some where and since i'm new to rails i don't get the code very much and for the life of me i cant see the error bro
@BroiSatse I know what's going on, but if you just provide code then when someone has a similar but not identical problem, and doesn't get it, this whole answer is useless. If you explain yourself, others can use it as well.
@fredo - How does the line with this code look like in your code? :) You might need to do map(&:first) in some cases.
@Humza - Also, your answer has O(n^2) complexity while all the other answers are O(n). :P
|
3
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]

Comments

3

Slow but clearly understandable (hopefully) to people new to Ruby:

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

Comments

0

Probably not the best solution, but:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.