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?

2

4 Answers 4

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

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

Comments

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

3 Comments

@mortezaT, that would be a different question, you may ask :)
This works perfectly with OP's terms (so deserves upvote). But is there any way to compare complex number and other characters. for example '1.1', '1.2', '1.3', ... , '1.10', ..., '2.20.21'
I will if you can answer it with SQL syntax :p.
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;
}

Comments

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

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.