Search code examples
rubyarraysenumerable

Find set of objects in array that have same attributes


Given that I have an array with two attributes: 'n_parents' and 'class', which looks like this:

my_arr = [{n_parents: 10, class: 'right'}, {n_parents: 10, class: 'right'}, {n_parents: 5, class: 'left'}, {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}]

I would like to get an array with the objects that share most of those two attributes. So in the previous example:

result = [{n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}]

Because there are three objects that share n_parents = 2, and class = 'center'.

So far, I know how can I group by dos two attributes, but after that I am not sure how to get the set that has more elements.

Right now I have:

my_arr.group_by { |x| [x[:n_parents], x[:class]] }

Solution

  • This should work for you. It groups the hashes by the hash itself and then gets the largest group by the array count

     my_arr = [{n_parents: 10, class: 'right'}, {n_parents: 10, class: 'right'}, {n_parents: 5, class: 'left'}, {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}, {n_parents: 2, class: 'center'}]
     my_arr.group_by { |h| h }.max_by { |h,v| v.count }.last
     #=>[{:n_parents=>2, :class=>"center"}, {:n_parents=>2, :class=>"center"}, {:n_parents=>2, :class=>"center"}]