Siva
Siva

Reputation: 289

Custom List sorting

Hi I have a list which contains elements [daily,monthly,weekly] or [monthly,weekly,daily] or [weekly,daily]

I need to sort the list in such a way that

[daily,monthly,weekly] == [daily,monthly,weekly]

[monthly, weekly, daily] == [daily, monthly, weekly]

[weekly, daily] == [daily, weekly]

Can some one please help me in this

Upvotes: 4

Views: 2895

Answers (1)

tim_yates
tim_yates

Reputation: 171074

Assuming you mean that you have a list of Strings, then this should work:

customSorter = { 
  [ 'daily', 'monthly', 'weekly' ].indexOf( it )
}

assert [ 'daily', 'monthly', 'weekly' ].sort( customSorter ) == [ 'daily', 'monthly', 'weekly' ]
assert [ 'monthly', 'weekly', 'daily' ].sort( customSorter ) == [ 'daily', 'monthly', 'weekly' ]
assert [ 'weekly', 'daily' ].sort( customSorter ) == [ 'daily', 'weekly' ]

Or you could do this (to avoid repeatedly creating a List)

customSorter = { a, b, order=['daily','monthly','weekly'] ->
  order.indexOf( a ) <=> order.indexOf( b )
}

Upvotes: 6

Related Questions