Seigs Seigs - 7 months ago 28
Javascript Question

Sort an array of strings alphabetically, numerically then by special characters

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?

Answer

Here's my stab at what you're looking for. I think it's a bit cleaner than what you have:

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", " ", "-", "'", "(", "[", "`"]