2

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.

Community
  • 1
  • 1
CARTIC
  • 573
  • 3
  • 14
  • 26

3 Answers3

3

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*/ 
});
Ashwin Prabhu
  • 9,285
  • 5
  • 49
  • 82
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"]
Bruno
  • 5,772
  • 1
  • 26
  • 43
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/

Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43