给定以下字符串数组,我一直尝试自然地对a-z字符串进行排序,然后是数字字符串,最后是特殊字符.
nextSearchTerms = ["T","D","I","C","Y","O","4","K","N","800","S","1","V","(","10","'","`","B","M","[","-"," ","J","U","H","G","R","E","P"];
console.log(nextSearchTerms);
Array.prototype.naturalSort = function(){
var a, b, a1, b1, rx=/(\d+)|(\D+)/g, rd=/\d+/;
return this.sort(function(as, bs){
a= String(as).toLowerCase().match(rx);
b= String(bs).toLowerCase().match(rx);
while(a.length && b.length){
a1= a.shift();
b1= b.shift();
if (rd.test(a1) || rd.test(b1)){
if(!rd.test(a1)) return -1;
if(!rd.test(b1)) return 1;
if(a1 != b1) return a1-b1;
}
else if (a1 != b1) {
var aIsLetter = a1[0].charAt(0).match(/[a-z]/i),
bIsLetter = b1[0].charAt(0).match(/[a-z]/i);
if (aIsLetter && !bIsLetter) return -1;
if (!aIsLetter && bIsLetter) return 1;
return (a1[0] == b1[0] ? 0 : (a1[0] < b1[0] ? -1 : 1));
}
}
return a.length - b.length;
});
}
console.log(nextSearchTerms.naturalSort());
我一直试图修改的函数返回.
[“B”,“C”,“D”,“E”,“G”,“H”,“I”,“J”,“K”,“M”,“N”,“O”,“ P“,”R“,”S“,”T“,”U“,”V“,”Y“,”“,”’“,”(“,” – “,”[“,”`“, “1”,“4”,“10”,“800”]
我想最终的数组输出.
[“B”,“C”,“D”,“E”,“G”,“H”,“I”,“J”,“K”,“M”,“N”,“O”,“ P“,”R“,”S“,”T“,”U“,”V“,”Y“,”1“,”4“,”10“,”800“,”’“,”“ ,“ – ”,“[”,“`”,“”]
关于我缺少什么的任何建议?
最佳答案 这是我对你所寻找的东西的刺激.我认为它比你拥有的更清洁:
Array.prototype.naturalSort = function() {
var stringRE = /^[A-Za-z]+$/
var numberRE = /^[\d]+$/
return this.sort(function(a, b) {
var aIsString = stringRE.test(a);
var bIsString = stringRE.test(b)
var aIsNumeric = numberRE.test(a);
var bIsNumeric = numberRE.test(b);
if (aIsString && bIsString) {
return a.localeCompare(b);
} else if (aIsNumeric && bIsNumeric) {
return parseInt(a, 10) - parseInt(b, 10);
} else if (aIsString && bIsNumeric) {
return -1;
} else if (aIsNumeric && bIsString) {
return 1;
} else if (aIsString || aIsNumeric) {
return -1;
} else if (bIsString || bIsNumeric) {
return 1;
} else {
return a.localeCompare(b);
}
})
};
var chars = ["T","D","I","C","Y","O","4","K","N","800","S","1","V","(","10","'","`","B","M","[","-"," ","J","U","H","G","R","E","P"];
console.log(chars.naturalSort());
// ["B", "C", "D", "E", "G", "H", "I", "J", "K", "M", "N", "O", "P", "R", "S", "T", "U", "V", "Y", "4", "1", "10", "800", " ", "-", "'", "(", "[", "`"]