Search code examples
rubyarraysgrouping

Group a 2D array


I have the following kind of array

[[y,x], [y,w], [m,e], [m,t],[a,b]]

How would I turn it to

[[y, [x,w]], [m, [e,t]], [a,[b]]

essentially grouping all arrays by their 1st element


Solution

  • Using Enumerable#group_by:

    a = [['y','x'], ['y','w'], ['m','e'], ['m','t'],['a','b']]
    a.group_by(&:first).map { |c, xs| [c, xs.map(&:last)] }
    # => [["y", ["x", "w"]], ["m", ["e", "t"]], ["a", ["b"]]]