Search code examples
rubyarraystransformation

Transform nested arrays in Ruby to group items with the same id


I have an array:

[[1,"Location1"],[1,"Location2"],[1,"Location3"],[2,"Location4"],[2,"Location5"],[2,"Location6"]]

How can I map this array so that I get:

[[1,["Location1", "Location2", "Location3"]],[2,["Location4", "Location5", "Location6"]]]

Solution

  • Do as below :-

    array = [[1,"Location1"],[1,"Location2"],[1,"Location3"],[2,"Location4"],[2,"Location5"],[2,"Location6"]]
    array.group_by(&:first).map { |k, v_ary| [k, v_ary.map(&:last)] }
    # => [[1, ["Location1", "Location2", "Location3"]], [2, ["Location4", "Location5", "Location6"]]]
    

    or

    array.each_with_object(Hash.new { |hsh, key| hsh[key] = [] }) { |(f,l), h| h[f] << l }.to_a
    # => [[1, ["Location1", "Location2", "Location3"]], [2, ["Location4", "Location5", "Location6"]]]