user749798
user749798

Reputation: 5380

Sort hashes in array alphabetically by a field

I'd think this would be easy, and have searched for this pretty hard, but can't seem to get it to work.

I have the following hash:

@friends = [{"name"=>"John Smith", "id"=>"12345"}, {"name"=>"Jane Doe", "id"=>"23456"}, {"name"=>"Samuel Jackson", "id"=>"34567"}, {"name"=>"Kate Upton", "id"=>"45678"}]

I'm trying to sort it alphabetically by the name.

Right now I"m doing this:

@friends.sort{|a,b| a[0]<=>b[0]}

However, it just outputs the full results in non-alphabetical order.

Upvotes: 5

Views: 5661

Answers (2)

Ismael
Ismael

Reputation: 16730

The problem is that a and b are Hash, so you have to use "name" as the key or index instead of 0. So this should do it

@friends.sort{|a,b| a['name']<=>b['name']}

Also remember to use sort! to modify @friends variable or set it to the result

@friends.sort!{|a,b| a['name']<=>b['name']}

or

@friends = @friends.sort{|a,b| a['name']<=>b['name']}

Upvotes: 12

Matenia Rossides
Matenia Rossides

Reputation: 1414

It is possible to sort by a key, just be aware if the key is a string or a symbol when doing this.

@friends.sort_by { |f| f['name'] }

If you want to make it case insensitive then you can always do:

@friends.sort_by { |f| f['name'].downcase }

And of course you can always use ! to save that back to @friends

>> @friends.sort_by! { |f| f['name'] }
>> @friends # now returns the sorted array of hashes

Upvotes: 7

Related Questions