Skip to content
Nate
Stephens

Sorting Strings

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)

MDN docs

locales documentation

options documentation

Returns:

  • Negative integer when the referenceStr occurs before compareString
  • Positive integer when the referenceStr occurs after compareString
  • 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 without new. Both create a new Intl.Collator instance.

Intl.Collator() constructor docs


Last Updated: