1

Possible Duplicate:
Sort mixed alpha/numeric array

I'm trying to sort an array which contains elements in the form of xxx1, xxx2, xxx3. The Array.sort() method works fine until xxx9 and if there is an element by name xxx10 or xxx11, it fails. The order comes as xxx1, xxx10, xxx11, xxx2 and so on. Please let me know how to fix this.

2
  • 3
    That is expected behavior. Look for a natural sorting implementation. Commented Nov 5, 2012 at 11:28
  • post some code. I think you need to convert your numbers. Commented Nov 5, 2012 at 11:33

3 Answers 3

2

You are seeing the results of natural string sorting. If string sort is not what you want, you should be using your own comparator.

Do something like:

arrayToBeSorted.sort(function(first,second)
{ 
  /* some code that compares 'first' with 'second' and returns <0, ==0, >0*/ 
});
Sign up to request clarification or add additional context in comments.

Comments

0

At the moment your array is being sorted alphabetically which is why you are getting those results. You need to provide your own comparator function to implement a numerical sort.

Try

var arr = ["xxx1","xxx10","xxx2","xxx20","xxx3","xxx30"];

var sortedArr = arr.sort( function( a, b ) {

    // remove first 3 characters so remaining string will parse
    a = parseInt( a.substr( 3 ) );
    b = parseInt( b.substr( 3 ) );

    return a - b;
});

console.log( sortedArr ); // => ["xxx1", "xxx2", "xxx3", "xxx10", "xxx20", "xxx30"]

Comments

0

You can implement custom sorting condition in callback to pass into Array.sort():

​var arr = [],
    re = /^\D*(\d+)$/;

for(var i = 20; i-- > 0;) {
    arr.push('xxx' + i);
}

function comparator(a, b) {
    var numA = a.match(re)[1],
        numB = b.match(re)[1];
    return numA - numB;
}

arr.sort(comparator);
console.log(arr);
​

http://jsfiddle.net/f0t0n/qz62J/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.