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

2
  • 1
    What if it had more than 9 digits or leading zeros? I think what you really need here is natural sorting.
    – Kobi
    Jul 20, 2012 at 6: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, 2012 at 7:15

1 Answer 1

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 :-)

1
  • Thanks for your commitment. You definitly get the quickest-answer-price.
    – heinob
    Jul 20, 2012 at 7:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.