(我之前也问过这个问题here但是被标为重复,但是这个答案不符合我的要求)
我有一个数组 a=["Apple","Mango","apple","mango"]
。如果我使用 a.sort()
结果是
["苹果", "芒果", "苹果", "芒果"]
但我想要的是
Apple,apple,Mango,mango
记住敏感排序不是大小写,因为无论给定元素在数组中的顺序是什么,输出都应该是
苹果 苹果 芒果 芒果 意思是大写字母应该在小写字母之前
最佳答案
然后您的比较器需要进行两轮比较。
a.sort(function(e1, e2) {
var ce1 = e1.toLowerCase(), ce2 = e2.toLowerCase();
if (ce1 < ce2) return -1;
if (ce1 > ce2) return 1;
// at this point, we know that the two elements are the same
// except for letter case ...
if (e1 < e2) return -1;
if (e1 > e2) return 1;
return 0;
});
函数首先检查转换为小写后的两个元素。如果它们在转换为小写后相等,它会检查原始形式。因此,“Apple”和“apple”将在第一轮比较相等,因此将被排序为“Apple”排在第一位。
关于javascript - 在javascript中自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25383344/