Devin Gray Devin Gray - 23 days ago 5
Ruby Question

Adding arrays of hashes and sort by hash value

I have two arrays

arrayOne = [{:name=>"name1", :id=>1}, {:name=>"name2", :id=>2}, {:name=>"name3", :id=>3}]

arrayTwo = [{:name=>"name2.1", :id=>1}, {:name=>"name2.2", :id=>2}, {:name=>"name2.3", :id=>3}]


And I want to flatten and sort these two arrays into one big array so I tried this

@bigArray = [arrayOne, arrayTwo].flatten.sort {|a,b| a.name <=> b.name}


However this does not work. I am new to rails and am unsure about the above
flatten.sort
should it be mapped?
Is there a better way to do this?

Answer
(arrayOne + arrayTwo).sort_by { |e| e[:name] }
#=> [{:name=>"name2.1", :id=>1},
#    {:name=>"name2.1", :id=>1},
#    {:name=>"name2.2", :id=>2},
#    {:name=>"name2.2", :id=>2},
#    {:name=>"name2.3", :id=>3},
#    {:name=>"name2.3", :id=>3}]