Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphabetical order in array with multiple defaults on top

Tags:

arrays

ruby

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.

like image 413
Michael Koper Avatar asked Jan 28 '26 15:01

Michael Koper


2 Answers

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.

like image 81
the Tin Man Avatar answered Jan 30 '26 07:01

the Tin Man


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"]
like image 31
Anthony Alberto Avatar answered Jan 30 '26 09:01

Anthony Alberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!