const strArray = ['red', 'white', 'blue'];
const sorted = [...strArray].sort((a, b) => a.localeCompare(b));
// sorted === [ 'blue', 'red', 'white' ]String.prototype.localeCompare()
<referenceStr>.localeCompare(compareString, locales, options)
Returns:
- Negative integer when the
referenceStroccurs beforecompareString - Positive integer when the
referenceStroccurs aftercompareString 0if they are equivalent
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 its compare() method.
Intl.Collator
String.prototype.localeCompare(compareString, locales, options) simply calls Intl.Collator.
It's equivalent to new Intl.Collator(locales, options).compare(referenceStr, compareString).
const strArray = ['red', 'white', 'blue'];
const sorted = [...strArray].sort(new Intl.Collator().compare);
// sorted === [ 'blue', 'red', 'white' ]NOTE:
Intl.Collator()can be called with or withoutnew. Both create a newIntl.Collatorinstance.
Intl.Collator() constructor docs↗