我使用这个按字母顺序对数组进行排序:
contactList.sort((function(index){
return function(a, b){
return (a[index] == b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
};
})(2));
它工作得很好,唯一的问题是数字和特殊字符出现在我的数组的顶部。我希望它按字母顺序排序,但我也希望它在末尾存储数字和特殊字符。
我真的不知道如何修改我的函数来做到这一点。
最佳答案
检查一下,它们是否是字母。
我只检查第一个字符,但也许您需要扩展此检查以区分大小写
a[index].charAt(0) == b[index].charAt(0)
在循环中比较以下字母等。
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));
关于javascript - 按字母顺序对数组进行排序,将数字和特殊字符保留在末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16190005/