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.
Arrays of objects can be sorted by comparing the value of one of their properties.
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.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With