Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort months ( with strings ) algorithm

I have this months array:

["January", "March", "December" , "October" ]

And I want to have it sorted like this:

["January", "March", "October", "December" ] 

I'm currently thinking in a "if/else" horrible cascade but I wonder if there is some other way to do this.

The bad part is that I need to do this only with "string" ( that is, without using Date object or anything like that )

What would be a good approach?

like image 540
OscarRyz Avatar asked Jan 20 '10 00:01

OscarRyz


1 Answers

If I had a way to supply a custom sorting order, I'd create a list defining the correct order:

correct = List("January", "February", "March", ...)

And then sort by the position in that list, something like:

toSort.sort(a, b) => compare(correct.index(a), correct.index(b))
like image 169
Fabian Steeg Avatar answered Sep 22 '22 06:09

Fabian Steeg