Sometimes, we want to compare 2 strings alphabetically for sorting purposes with JavaScript.
In this article, we’ll look at how to compare 2 strings alphabetically for sorting purposes with JavaScript.
Compare 2 Strings Alphabetically for Sorting Purposes with JavaScript with the localeCompare Method
We can compare 2 strings alphabetically for sorting with the localeCompare
method.
For instance, we can write:
const arr = ['foo', 'bar', 'baz']
const sorted = arr.sort((a, b) => a.localeCompare(b))
console.log(sorted)
to use localeCompare
to compare strings a
and b
in the comparator callback we pass into the sort
method.
It’ll return -1 is a
before b
alphabetically, 0 if they’re the same, and 1 otherwise.
Then we get that sorted
is:
["bar", "baz", "foo"]
as a result.
Conclusion
We can compare 2 strings alphabetically for sorting with the localeCompare
method.