Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort hashes in array alphabetically by a field

Tags:

ruby

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.

like image 496
user749798 Avatar asked Jul 04 '12 23:07

user749798


2 Answers

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']}
like image 197
Ismael Avatar answered Nov 12 '22 09:11

Ismael


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
like image 40
Matenia Rossides Avatar answered Nov 12 '22 08:11

Matenia Rossides