假设我们有以下数组
let names = ['Malek', 'malek', 'sana', 'ghassen', 'Ghada', 'Samir'];
console.log(names.sort());
结果如下:
["Ghada", "Malek", "Samir", "ghassen", "malek", "sana"]
JavaScript根据每个字符的ASCII值对其进行比较。
我要按小写字母排序,以排在排序数组的首位
预期输出:
["Ghada", "ghassen", "malek", "Malek", "Samir", "sana"]
谢谢
答案 0 :(得分:9)
尝试使用 localeCompare :
const names = ["Ghada", "Malek", "Samir", "ghassen", "malek", "sana"];
const result = names.sort((a, b) => a.localeCompare(b));
console.log(result);
localeCompare()方法返回一个数字,该数字指示该字符串按排序顺序位于compareString之前,之后还是相等。
答案 1 :(得分:1)
尝试为,
let names = ['Malek', 'malek', 'sana', 'ghassen', 'Ghada', 'Samir'];
console.log(names.sort(function(a, b) {
var nameA = a.toUpperCase(); // ignore upper and lowercase
var nameB = b.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
}));
答案 2 :(得分:0)
您可以使用Intl.Collator()
:
let names = ['Malek', 'malek', 'sana', 'ghassen', 'Ghada', 'Samir', "A", 'a', 'ba', 'Ba', 'Cd', 'ca'];
let res = names.sort(Intl.Collator('en').compare);
console.log(res);