How to get localeCompare to behave similarly to .sort(), so that all capital letters come first?

流过昼夜 提交于 2020-01-14 10:48:14

问题


I have an array of characters I want to sort:

const arr = ['z', 'a', 'Z', 'A'];

I want the sorted order to be: upper-case characters alphabetically, followed by lower-case characters alphabetically:

['A', 'Z', 'a', 'z']

This is trivial to accomplish using .sort() without any parameters:

const arr = ['z', 'a', 'Z', 'A'];
arr.sort();
console.log(arr);

But how could localeCompare be used to determine the same relative position of each character? The caseFirst option looked promising:

Whether upper case or lower case should sort first. Possible values are "upper", "lower", or "false" (use the locale's default); the default is "false". This option can be set through an options property or through a Unicode extension key; if both are provided, the options property takes precedence.

But it doesn't appear to do what I want. I've tried many variants:

// Desired result: ['A', 'Z', 'a', 'z']

const arr = ['z', 'a', 'Z', 'A'];
arr.sort((a, b) => a.localeCompare(b));
console.log(arr);
arr.sort((a, b) => a.localeCompare(b, undefined, { caseFirst: 'upper' }));
console.log(arr);
arr.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'case', caseFirst: 'upper' }));
console.log(arr);
arr.sort((a, b) => a.localeCompare(b, 'en', { caseFirst: 'upper' }));
console.log(arr);
arr.sort((a, b) => a.localeCompare(b, 'kf', { caseFirst: 'upper' }));
console.log(arr);

I'd like it to perform similarly to .sort() (at least for alphabetical characters), which compares each character's code point:

['A', 'Z', 'a', 'z'].forEach((char) => {
  console.log(char.charCodeAt());
});

Of course, I know I can simply avoid localeCompare and use .sort() without a callback, or use the charCodeAt method above:

const arr = ['z', 'a', 'Z', 'A'];
arr.sort((a, b) => a.charCodeAt() - b.charCodeAt());
console.log(arr);

But how would I do it using localeCompare?

来源:https://stackoverflow.com/questions/54975581/how-to-get-localecompare-to-behave-similarly-to-sort-so-that-all-capital-let

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!