我有一个字符串数组,即章节序列。我应该按顺序对数组进行排序。
示例
var item = ["1.1", "1.1.1", "17.10", "13.11", "11.12", "17.7.a", "6.11", "6.11.1", "1.2", "1.2.1", "1.2.2.a"]
console.log("After Sort : " + item.sort());
但预期结果是
["1.1", "1.1.1", "1.2", "1.2.1", "1.2.2.a", "6.11", "6.11.1", "11.12", "13.11", "17.7.a", "17.10"]
更新
我从这个reference
得到了答案Array.prototype.humanSort = function() {
return this.sort(function(a, b) {
aa = a.split(/(\d+)/);
bb = b.split(/(\d+)/);
for(var x = 0; x < Math.max(aa.length, bb.length); x++) {
if(aa[x] != bb[x]) {
var cmp1 = (isNaN(parseInt(aa[x],10)))? aa[x] : parseInt(aa[x],10);
var cmp2 = (isNaN(parseInt(bb[x],10)))? bb[x] : parseInt(bb[x],10);
if(cmp1 == undefined || cmp2 == undefined)
return aa.length - bb.length;
else
return (cmp1 < cmp2) ? -1 : 1;
}
}
return 0;
});
}