Question

Let's say in my rails app I have 50 different Topics, each identified with topic_id. Let's also say that this following query returns 50 posts and selects topic_id from each.

Post.where(id: something).select(:topic_id)

How then do I rank top 5 topic_ids that most often come up from this query?

Was it helpful?

Solution

This works, but there may be a more efficient way to do it - feel free to chime in with suggestions, I'm new!

[1,2,2,2,3,4,5,6,6,6,6].group_by{|x| x}.sort_by{|k,v| -v.size}[0..4][0..4].map{|arr| arr[0] }

Groups the values, sorts by the size of the groups, then extracts the topic_ids from the resulting arrays. Result is an array of topic_ids sorted by frequency.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top