0

I want to sort an array of strings that contain names and numbers. But I want to improve the alphanumerical sort order to get an order like

John 8 test
John 9 test
John 10 test

instead of having "John 10 test" at the top because "1" < "8" < "9". My idea is to insert the number of digits of a number bevore any number so internally the array to be sorted becomes:

John 18 test
John 19 test
John 210 test

which now is an alphanumeric correctly sorted array.

Any ideas how to insert the number of digits bevore the numer in an easy way? RegExp would be perfect. I am doing all this in nodejs/JavaScript.

Thanks in advance!

heinob

heinob
  • 19,127
  • 5
  • 41
  • 61
  • 1
    What if it had more than 9 digits or leading zeros? I think what you really need here is [natural sorting](http://stackoverflow.com/q/2802341/7586). – Kobi Jul 20 '12 at 06:48
  • This actually could be a problem but does not happen in my case, because the numbers are physical measurement values, which have no leading zeros and don't tend to have more than 9 digits. – heinob Jul 20 '12 at 07:15

1 Answers1

1

I found the (one) answer myself:

var a = "John 352 Name 1 test 23 better";
a.replace( /\d+/g, function( match, number) {
    return match.length + match;
});

Does what I want :-)

heinob
  • 19,127
  • 5
  • 41
  • 61