First sort specific array elements

I have a ruby โ€‹โ€‹array that looks something like this:

my_array = ['mushroom', 'beef', 'fish', 'chicken', 'tofu', 'lamb'] 

I want to sort the array so that "chicken" and "beef" are the first two elements, then the rest of the elements are sorted alphabetically. How can i do this?

+4
source share
4 answers
 irb> my_array.sort_by { |e| [ e == 'chicken' ? 0 : e == 'beef' ? 1 : 2, e ] } #=> ["chicken", "beef", "fish", "lamb", "mushroom", "tofu"] 

This will create a sort key for each element of the array, and then sort the array elements by their sort keys. Since the sort key is an array, it is compared by position, so [0, 'chicken'] < [1, 'beef'] < [2, 'apple' ] < [2, 'banana'] .

If you donโ€™t know which elements you wanted to sort to the front before execution, you can still use this trick:

  irb> promotables = [ 'chicken', 'beef' ] #=> [ 'chicken', 'beef' ] irb> my_array.sort_by { |e| [ promotables.index(e) || promotables.size, e ] } #=> ["chicken", "beef", "fish", "lamb", "mushroom", "tofu"] irb> promotables = [ 'tofu', 'mushroom' ] #=> [ 'tofu', 'mushroom' ] irb> my_array.sort_by { |e| [ promotables.index(e) || promotables.size, e ] } #=> [ "tofu", "mushroom", "beef", "chicken", "fish", "lamb"] 
+10
source

Mine is much more general and more useful if you only get your data at runtime.

 my_array = ['mushroom', 'beef', 'fish', 'chicken', 'tofu', 'lamb'] starters = ['chicken', 'beef'] starters + (my_array.sort - starters) # => ["chicken", "beef" "fish", "lamb", "mushroom", "tofu"] 
+6
source

Another way to solve this problem:

 array = [1,2,2,3,3,4,5] array.select {|element| element == 2} + array.select {|element| element != 2} # => [2, 2, 1, 3, 3, 4, 5] 
+1
source

Can just do

 firsts = ["chicken", "beef"] [*firsts, *(my_array.sort - firsts)] #=> ["chicken", "beef", "fish", "lamb", "mushroom", "tofu"] 
+1
source

Source: https://habr.com/ru/post/1309592/


All Articles