Xion
Xion

Reputation: 494

Sorting array in IE

I have one array called myArr in my javascript like below.

["ob1","ob10","ob4","ob5","ob12"]

When I do sorting on this array, it doesn't sort in order of the number because it is a string number. Therefore I use below method to sort the array and now it works.

var collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
myArr .sort(collator.compare);

However this method is not suported in IE9. Is there any method that i can use to sort this kind of array in IE?

Upvotes: 1

Views: 277

Answers (1)

Michael Geary
Michael Geary

Reputation: 28870

If your array elements all follow that pattern of some non-digits followed by some decimal digits, then you could could do it by splitting the string into the non-digit and numeric parts, then first comparing on the non-digit part and then on the numeric part. (If the non-digit part is always "ob" it could be even simpler, but I'm allowing for other strings here.)

var array = ["ob1","ob10","ob4","ob5","oc10","ob12","oc4"];

var re = /(\D+)(\d+)/;

var sorted = array.sort( function( a, b ) {
    var aa = a.match( re );
    var bb = b.match( re );
    return(
        aa[1] < bb[1] ? -1 :
        aa[1] > bb[1] ? +1 :
        aa[2] - bb[2]
    );
});

console.log( sorted );

Upvotes: 2

Related Questions