user4796879
user4796879

Reputation:

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?

Upvotes: 1

Views: 58

Answers (2)

mattp
mattp

Reputation: 76

First off, the ruby syntax to access hash members is hash[key] rather than hash.key.

Secondly, since both of arrayOne and arrayTwo are arrays, you can just use the + operator on them and then do the sort. There's no need to make an intermediate array and then do a flatten.

Write it as:

bigArray = (arrayOne + arrayTwo).sort_by { |el| el[:name] }

Upvotes: 0

Andrey Deineko
Andrey Deineko

Reputation: 52357

(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}]

Upvotes: 1

Related Questions