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
?