Custom List sorting

后端 未结 1 1656
挽巷
挽巷 2020-12-21 08:59

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

I need to sort the

相关标签:
1条回答
  • 2020-12-21 09:33

    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 )
    }
    
    0 讨论(0)
提交回复
热议问题