Reputation: 3684
I'm sorting an Array alphabetically using this :
contactList.sort((function(index){
return function(a, b){
return (a[index] == b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
};
})(2));
It works great, the only problem is that numbers and special characters appear at the top of my array. I would like it to be sorted alphabetically, but I also want it to store the numbers & special chars at the end.
I really have no idea how to modify my function in order to do this.
Upvotes: 0
Views: 1379
Reputation: 14304
Just check, whether are they letters or not.
I'm checking only first character, but maybe you'll need to extend this check for case
a[index].charAt(0) == b[index].charAt(0)
to compare following letters and so on in loop.
contactList.sort((function(index){
return function(a, b){
var aIsLetter = a[index].charAt(0).match(/[a-z]/i),
bIsLetter = b[index].charAt(0).match(/[a-z]/i);
if (aIsLetter && !bIsLetter) return -1;
if (!aIsLetter && bIsLetter) return 1;
return (a[index] == b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
};
})(2));
Upvotes: 2