Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you sort an array of objects?

I have an object as follows:

[{:id=>2, :fname=>"Ron", :lname=>"XXXXX", :photo=>"XXX"}, {:id=>3, :fname=>"Dain", :lname=>"XXXX", :photo=>"XXXXXXX"}, {:id=>1, :fname=>"Bob", :lname=>"XXXXXX", :photo=>"XXXX"}] 

I want to sort this by fname, alphabetically case insensitive so it would result in

id: 1,3,2

How can I sort this? I'm trying:

@people.sort! { |x,y| y[:fname] <=> x[:fname] }

But that has no effect.

like image 938
AnApprentice Avatar asked Feb 16 '12 22:02

AnApprentice


People also ask

Can we sort array of objects?

Arrays of objects can be sorted by comparing the value of one of their properties.

How do you filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

You can use sort_by.

@people.sort_by! { |x| x[:fname].downcase }

(the downcase is for the case insensitivity)

For completeness, the issues with the provided code are:

  • the arguments are in the wrong order
  • downcase is not being called

The following code works using the sort method.

@people.sort! { |x,y| x[:fname].downcase <=> y[:fname].downcase }

As proof that both of these methods do the same thing:

@people.sort_by {|x| x[:fname].downcase} == @people.sort { |x,y| x[:fname].downcase <=> y[:fname].downcase }

Returns true.

like image 160
Gazler Avatar answered Sep 29 '22 16:09

Gazler