Given the following array of strings, I have been attempting to natural sort a-z strings first, followed by numerical strings and finally special characters.
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());
The function I have been attempting to modify currently returns.
["B", "C", "D", "E", "G", "H", "I", "J", "K", "M", "N", "O", "P", "R", "S", "T", "U", "V", "Y", " ", "'", "(", "-", "[", "`", "1", "4", "10", "800"]
I would like the final array output to be.
["B", "C", "D", "E", "G", "H", "I", "J", "K", "M", "N", "O", "P", "R", "S", "T", "U", "V", "Y", "1", "4", "10", "800", "'", "(", "-", "[", "`"," "]
Any suggestions on what I am missing?