Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby sort based on predefined list

Tags:

sorting

ruby

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.

like image 224
KJF Avatar asked Jan 18 '23 00:01

KJF


1 Answers

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"}]
like image 111
Aliaksei Kliuchnikau Avatar answered Jan 24 '23 19:01

Aliaksei Kliuchnikau