I have an array with strings and i would like it on alphabetical order but with some defaults on top. For example:
["a", "b", "default1", "d", "default2", "c", "e"]
and I would like the result to be:
["default1", "default2", "a", "b", "c", "d", "e"]
somebody has an idea how I can accomplish this easy?
UPDATE
The defaults are also included in the array and the array is in alphabetical order.
Enumerable includes partition:
data = ["a", "b", "default1", "d", "default2", "c", "e"]
data.partition{ |d| d['default'] }.flatten
=> ["default1", "default2", "a", "b", "d", "c", "e"]
If the data you get isn't sorted into the final order you want, you can pre-sort it before partitioning it:
data = ["c", "b", "default2", "a", "default1", "e", "d"]
data.sort.partition{ |d| d['default'] }.flatten
=> ["default1", "default2", "a", "b", "c", "d", "e"]
If you need a more intelligent and comprehensive sorting algorithm, to handle various "default" entries, you could probably use sort or sort_by with a lambda or proc that can tell the difference between the defaults and regular entries, and return the required -1, 0 and 1 values.
Something like this works :
array = ["a", "b", "default1", "d", "default2", "c", "e"]
defaults = ["default1", "default2"] #Add more if needed
sorted_array = array.sort{|a, b| defaults.include?(a) ? -1 : defaults.include?(b) ? 1 : a <=> b }
puts sorted_array # => ["default1", "default2", "a", "b" "c", "d", "e"]
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