1

I have the following array:

    var arr = ["COL10","COL5",
                "COL4","COL3",
                "COL8","COL9",
                "COL2","COL7",
                "COL1","COL6"];

    console.log("After sort:"+arr.sort());

The output is:

After sort:COL1,COL10,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9

But I want it to be:

After sort:COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10

How should I do this?

Tom Lord
  • 27,404
  • 4
  • 50
  • 77
Roth
  • 35
  • 4
  • I guess you need to define your custom comparator. Check this: http://stackoverflow.com/questions/17382091/javascript-sort-comparator-function – Vladimir Vagaytsev Jul 15 '16 at 08:08
  • check this link; http://stackoverflow.com/questions/4340227/sort-mixed-alpha-numeric-array/4340339#4340339 – msg Jul 15 '16 at 08:15

4 Answers4

2

Use the following approach with Array.sort and String.slice functions:

var arr = ["COL10","COL5","COL4","COL3","COL8","COL9","COL2","COL7","COL1","COL6"];

arr.sort(function (a,b) {
    return a.slice(3) - b.slice(3);
});

console.log(arr);
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

You could split the items and sort the parts separate.

var arr = ["COL10", "COL5", "COL4", "COL3", "COL8", "COL9", "COL2", "COL7", "COL1", "COL6"];

arr.sort(function (a, b) {
    var aa = a.split(/(\d+)/g),
        bb = b.split(/(\d+)/g);
    return aa[0].localeCompare(bb[0]) || aa[1] - bb[1];
});

console.log(arr);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Try out the alphanumerical sort from Brian Huisman: Article

var arr = ["COL10", "COL5",
  "COL4", "COL3",
  "COL8", "COL9",
  "COL2", "COL7",
  "COL1", "COL6"
];

console.log("After sort:" + arr.sort(alphanum));

function alphanum(a, b) {
  function chunkify(t) {
    var tz = [],
      x = 0,
      y = -1,
      n = 0,
      i, j;

    while (i = (j = t.charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >= 48 && i <= 57));
      if (m !== n) {
        tz[++y] = "";
        n = m;
      }
      tz[y] += j;
    }
    return tz;
  }

  var aa = chunkify(a);
  var bb = chunkify(b);

  for (x = 0; aa[x] && bb[x]; x++) {
    if (aa[x] !== bb[x]) {
      var c = Number(aa[x]),
        d = Number(bb[x]);
      if (c == aa[x] && d == bb[x]) {
        return c - d;
      } else return (aa[x] > bb[x]) ? 1 : -1;
    }
  }
  return aa.length - bb.length;
}
floooat
  • 41
  • 4
0
var arr = ["COL10","COL5",
                "COL4","COL3",
                "COL8","COL9",
                "COL2","COL7",
                "COL1","COL6"];

arr.sort(function(a,b) {
  var a1 = parseInt(a.split('COL')[1]);
  var b1 = parseInt(b.split('COL')[1]);
  return a1 - b1;
});
Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21