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
referenceStr
occurs beforecompareString
- Positive integer when the
referenceStr
occurs aftercompareString
0
if 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.Collator
instance.
Intl.Collator() constructor
docs↗