我需要按字母顺序对数据列表进行排序,但是在AaZz中,名称Antony
在名称antony
之前,而Zelda
在zelda
之前,所以列表看起来像这样:
- Abigail
- Antony
- abigail
- antony
- Zelda
- zelda
基本
list.sort(function (a, b) {
if (a.name > b.name) return -1;
if (a.name < b.name) return 1;
return 0;
});
正在生成这样的列表:
首选语言:Javascript
答案 0 :(得分:5)
有一个内置的:
let list = ["abigail", "Antony", "Abigail", "antony", "Zelda", "zelda"];
list.sort((a, b) =>
a.localeCompare(b, "en", { caseFirst: "upper" })
);
console.log(list);
编辑:也许您想要这个?
let list = ["abigail", "Antony", "Abigail", "antony", "Zelda", "zelda"];
const compareUpperFirst = (a, b) => {
if (a === "" && bb === "") return 0;
if (a === "") return -1;
if (b === "") return 1;
let aa = a.charAt(0);
let aal = aa.toLowerCase();
let bb = b.charAt(0);
let bbl = bb.toLowerCase();
if (aal < bbl) return -1;
if (aal > bbl) return 1;
if (aa < bb) return -1;
if (aa > bb) return 1;
return compareUpperFirst(a.substr(1), b.substr(1));
};
list.sort(compareUpperFirst);
console.log(list);