This isn’t anything new or innovative because it’s been in the language since ES1, but wanted to preserve it somewhere for reference.
Javascript offers the .localeCompare()
method on strings that not only compares strings from different languages, but will ignore case if you want it to and returns the proper sorting integer to return in a .sort()
callback.
MDN offers the following array sorting example:
const items = ['réservé', 'Premier', 'Cliché', 'communiqué', 'café', 'Adieu']; items.sort((a, b) => a.localeCompare(b, 'fr', { ignorePunctuation: true })); // ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']
It also has a note for performance:
When comparing large numbers of strings, such as in sorting large arrays, it is better to create an
Intl.Collator
object and use the function provided by itscompare()
method.