javascript natural sort

Razvan picture Razvan · Jan 30, 2013 · Viewed 7.4k times · Source

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?

Answer

elclanrs picture elclanrs · Jan 30, 2013

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