0

I'm having a array of string i.e. chapter sequence. I should sort the array in asc order.

Sample

var item = ["1.1", "1.1.1", "17.10", "13.11", "11.12", "17.7.a", "6.11", "6.11.1", "1.2", "1.2.1", "1.2.2.a"]

console.log("After Sort : " + item.sort());

But expected result is

["1.1", "1.1.1", "1.2", "1.2.1", "1.2.2.a", "6.11", "6.11.1", "11.12", "13.11", "17.7.a", "17.10"]

Updated

I got the answer from this reference

Array.prototype.humanSort = function() {
  return this.sort(function(a, b) {
    aa = a.split(/(\d+)/);
    bb = b.split(/(\d+)/);

    for(var x = 0; x < Math.max(aa.length, bb.length); x++) {
      if(aa[x] != bb[x]) {
        var cmp1 = (isNaN(parseInt(aa[x],10)))? aa[x] : parseInt(aa[x],10);
        var cmp2 = (isNaN(parseInt(bb[x],10)))? bb[x] : parseInt(bb[x],10);
        if(cmp1 == undefined || cmp2 == undefined)
          return aa.length - bb.length;
        else
          return (cmp1 < cmp2) ? -1 : 1;
      }
    }
    return 0;
  });
} 
Premkumar Jayaseelan
  • 681
  • 2
  • 10
  • 30

1 Answers1

0

Each item can easily be .split(".") to get an array of parts. This is something you can sort with.

Something like this would do it:

item.sort(function(a,b) {
    a = a.split(".");
    b = b.split(".");
    while(a.length && b.length) {
        if( a[0] == b[0]) {
            a.shift();
            b.shift();
            continue;
        }
        if( a[0] < b[0]) return -1;
        return 1;
    }
    if( b.length) return -1; // same items but b has more after that
    if( a.length) return 1;
    return 0;
});

This will give you the sort order you want.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592