Search code examples
arraysrubymultidimensional-arrayruby-on-rails-5filtering

Group/filter sub-arrays of a multidimensional array in Ruby/RoR


I have a Ruby on Rails query ending by a .pluck(:id, :title) and giving me an array full of 2-dimensions arrays like so :

array = [[11145, "string1"], [11223, "string1"], [11205, "string2"], [11127, "string2"], [11080, "string3"], [11158, "string3"]]

I'd like to group the IDs by title in order to get this result:

 [[[11145, 11223], "string1"], [[11205, 11127], "string2"], [[11080, 11158], "string3"]]

I've tried to concatenate the IDs directly in the SQL query or manipulate the array but didn't manage my expected result.

Any help is more than welcome. Thanks in advance.


Solution

  • Fast solution:

    array.group_by(&:last).transform_values { |e| e.map(&:first) }.to_a
    
    1. Enumerable#group_by
    2. Hash#transform_values

    One more variant is:

    array.each_with_object(Hash.new {|h,k| h[k] = [] }) do |obj, res|
      res[obj.last] << obj.first
    end.to_a
    
    1. Hash#default_proc
    2. Enumerable#each_with_object

    UPD I don't know how your query looks like, but if you work with PG, you can try to play with this ending of:

    .group(:title).select('array_agg(id) as ids, title').map { |e| [e.title, e.ids] }