Sometimes, we want to sort an array with arrays in it by string with JavaScript.
In this article, we’ll look at how to sort an array with arrays in it by string with JavaScript.
How to sort an array with arrays in it by string with JavaScript?
To sort an array with arrays in it by string with JavaScript, we use the localeCompare
method.
For instance, we write
const sorted = myArray.sort((a, b) => a.localeCompare(b));
to call myArray.sort
with a callback that gets the values a
and b
being looped through from the parameters.
Then we compare them with a.localeCompare(b)
to return a sorted array that sorts the strings in ascending order.
Conclusion
To sort an array with arrays in it by string with JavaScript, we use the localeCompare
method.