I have an array of objects
. Each object has an attribute we'll call display_name
.
I want to sort this array based on a predefined list of values.
So if the predefined list looks something like this ["Ball", "Cat", "Helicopter", "France"]
Then the objects with the display_name attribute matching "Ball"
with be at the head of the list, those with "Cat"
second in the list and so on and so forth.
You can use Enumerable#sort_by:
list = ["Ball", "Cat", "Helicopter", "France"]
elements = [{:display_name => 'Cat'}, {:display_name => 'Unknown'}, {:display_name => 'Ball'}]
# sort by index in the list. If not found - put as last.
elements.sort_by { |e| list.index(e[:display_name]) || list.length }
# => [{:display_name=>"Ball"}, {:display_name=>"Cat"}, {:display_name=>"Unknown"}]
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