Question

I have this array :

var columnArray =
['columnNumber1','columnNumber6','coulmnNumber7','columnNumber11','columnNumber12'];

If I do columnArray.sort();, it gives me :

columnArray:
['columnNumber1','columnNumber11','coulmnNumber12','columnNumber6','columnNumber7']

How can I sort it correctly?

Was it helpful?

Solution

Try like this:

arr = arr.sort(function(a, b) {
  return +/\d+/.exec(a)[0] - +/\d+/.exec(b)[0];
});

Edit: Fixed it works now, it had a couple errors: http://jsbin.com/iwejik/1/edit

OTHER TIPS

columnArray.sort(function(a,b) {
     return parseInt(a.match(/\d+/)[0],10) - parseInt(b.match(/\d+/)[0],10);
});

demo

There is a npm package for this : https://github.com/Bill4Time/javascript-natural-sort.Works quite fine on many scenarios.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top