javascript natural sort

我的梦境 提交于 2019-12-17 19:54:40

问题


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?


回答1:


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




回答2:


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

demo




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!