I have an array like;
["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]
And need to sort it so it appears like;
["IL0 Foo", "IL3 Bob says hello", "IL10 Baz", "PI0 Bar"]
I have tried a sort function;
function compare(a,b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
but this gives the order
["IL0 Foo", "IL10 Baz", "IL3 Bob says hello", "PI0 Bar"]
I have tried to think of a regex that will work but can't get my head around it.
If it helps the format will always be 2 letters, x amount of numbers, then any number of characters.
This is called "natural sort" and can be implemented in JS like this:
To sort in reverse order, just swap the arguments:
or simply
I liked georg's solution a lot, but I needed underscores ("_") to sort before numbers. Here's how I modified his code:
You could do a regex like this to get non-numeric and numeric parts of the string:
returns:
["foo", "124" , "bar" , "23"]
Then in your compare function you can iterate through the parts of the two strings comparing them part-by-part. The first non-matching part determines the result of the overall comparison. For each part, check if the part starts with a digit and if so parse it as a number before doing the comparison.
Not pretty, but check the first two char codes. If all equal parse and compare the numbers:
Example
You could use
String#localeCompare
withoptions