1

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?

3
  • You might have a look at developer.mozilla.org/de/docs/Web/JavaScript/Reference/…, but as you are using IE9, you maybe can't get around lodash.com/docs/3.10.1 EDIT If you are using lodash, make sure to use 3.10.1, because IE9 support was removed in v4 Commented Jan 17, 2018 at 10:13
  • Why can't you write your own comparator? I think it could be as simple as this: myArr.sort( function(a, b) { var an = parseInt(a.replace( /^\D+/g, '')); var bn = parseInt(b.replace( /^\D+/g, '')); return bn - an; }) Commented Jan 17, 2018 at 10:15
  • Try with this arr.sort((a,b) => a.localeCompare(b, undefined, {numeric: true})); Commented Jan 17, 2018 at 10:40

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.