ikhvjs
ikhvjs

Reputation: 5947

Sort array alphabetically, then by uppercase and then by lowercase

I would like to sort an array alphabetically, then by uppercase and then by lowercase.

const i = ["aA", "BA", "Aa", "aa", "Ba", "AA"];

//I tired so far.
i.sort((a, b) => a.localeCompare(b));

console.log(i);

//expected output
const o = ["AA", "Aa", "aA", "aa", "BA", "Ba"];

Upvotes: 2

Views: 1060

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97152

You can use the caseFirst option to specify that upper-case letters take priority over lower-case letters:

const i = ["aA", "BA", "Aa", "aa", "Ba", "AA"];

i.sort((a, b) => a.localeCompare(b, 'en-US', {caseFirst: 'upper'}));

console.log(i);

Upvotes: 5

Related Questions