Toby Joiner
Toby Joiner

Reputation: 4376

Sort rails hash based on array of items

I have an array like this:

['one','three','two','four']

I have a array of hash like this:

[{'three' => {..some data here..} }, {'two' => {..some data here..} }, {:total => some_total }] # etc...

I want to sort the array of hashes by the first array. I know I can do:

array_of_hashes.sort_by{|k,v| k.to_s} to sort them and it will sort by the key 

( and the .to_s to convert :total to a string )

How can I make this happen?

Edit:

I was incorrect about how this is setup, it is actually like this:

{'one' => {:total => 1, :some_other_value => 5}, 'two' => {:total => 2, :some_other_value => 3} }

If I need to put this in a new question, just let me know and I will do that.

Thank you

Upvotes: 2

Views: 1908

Answers (2)

amitkaz
amitkaz

Reputation: 2712

similar to ctcherry answer, but using sort_by.

sort_arr = ['one','three','two','four']
hash_arr = [{'three' => {..some data here..} }, {'two' => {..some data here..} }]

hash_arr.sort_by { |h| sort_arr.index(h.keys.first) }

Upvotes: 6

Chris Cherry
Chris Cherry

Reputation: 28574

The index method of Array is your friend in this case:

sort_list = ['one','three','two','four']

data_list = [{'three' => { :test => 3 } }, {'two' => { :test => 2 } },  {'one' => { :test => 1 } },  {'four' => { :test => 4 } }]

puts data_list.sort { |a,b|
 sort_list.index(a.keys.first) <=> sort_list.index(b.keys.first)
}.inspect

Resulting in, the same order as the source array:

[{"one"=>{:test=>1}}, {"three"=>{:test=>3}}, {"two"=>{:test=>2}}, {"four"=>{:test=>4}}]

Upvotes: 0

Related Questions