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.
Fast solution:
array.group_by(&:last).transform_values { |e| e.map(&:first) }.to_a
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
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] }