Categories
JavaScript Answers

How to sort an array with arrays in it by string with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *