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?
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
columnArray.sort(function(a,b) {
return parseInt(a.match(/\d+/)[0],10) - parseInt(b.match(/\d+/)[0],10);
});
There is a npm package for this : https://github.com/Bill4Time/javascript-natural-sort.Works quite fine on many scenarios.
来源:https://stackoverflow.com/questions/14599321/javascript-natural-sort