Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort specific items of an array first

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 items, then the remaining items are sorted alphabetically. How would I go about doing this?

like image 287
Matt Huggins Avatar asked May 12 '10 18:05

Matt Huggins


People also ask

How do you sort a specific part of an array?

Arrays. sort() method can be used to sort a subset of the array elements in Java. This method has three arguments i.e. the array to be sorted, the index of the first element of the subset (included in the sorted elements) and the index of the last element of the subset (excluded from the sorted elements).

How do I sort an array from a specific index?

To sort an array only in specified index range, you can call Arrays. sort() method and pass the arguments: array, starting-index and to-index to the method. arr is the array of elements. The array could be of type byte, char, double, integer, float, short, long, object, etc.

How do you sort an array of objects based on property?

Example 1: Sort Array by Property Name The sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case). Here, The property names are changed to uppercase using the toUpperCase() method. If comparing two names results in 1, then their order is changed.

How do you take the first element of an array?

Passing a parameter 'n' will return the first 'n' elements of the array. ES6 Version: var first = (array, n) => { if (array == null) return void 0; if (n == null) return array[0]; if (n < 0) return []; return array. slice(0, n); }; console.


1 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 sorting key for each element of the array, and then sort the array elements by their sorting keys. Since the sorting key is an array, it compares by position, so [0, 'chicken'] < [1, 'beef'] < [2, 'apple' ] < [2, 'banana'].

If you don't know what elements you wanted sorted to the front until runtime, 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"]
like image 157
rampion Avatar answered Oct 03 '22 21:10

rampion