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?

Xion
  • 452
  • 2
  • 6
  • 25
  • You might have a look at https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare, but as you are using IE9, you maybe can't get around https://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 – scipper Jan 17 '18 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; })` – Tibrogargan Jan 17 '18 at 10:15
  • Try with this `arr.sort((a,b) => a.localeCompare(b, undefined, {numeric: true}));` – Hassan Imam Jan 17 '18 at 10:40

1 Answers1

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 );
Michael Geary
  • 28,450
  • 9
  • 65
  • 75