DEV Community

Cover image for How to sort an array of strings with non-latin letters?
Maciej Trzciński 🌱🇵🇱
Maciej Trzciński 🌱🇵🇱

Posted on • Originally published at Medium

How to sort an array of strings with non-latin letters?

JavaScript has a native sort method, you can do it with array.sort(), it will sort the array alphabetically. Also, you can provide your custom sorting functionality.

But if you want to order an array of non-ASCII character like [‘ą’, ‘ę’, ‘ó’, ‘ż’, ‘ź’, ‘e’], you will receive a [“e”, “ó”, “ą”, “ę”, “ź”, “ż”]. That happened because sort function works only with the English alphabet.

Fortunately, there are two ways to overcome this behavior localeCompare and Intl.Collator provided by ECMAScript Internationalization API.

Using localeCompare()

Using Intl.Collator()

So when you are working with arrays of strings in a language different from English, remember to use these methods to avoid unexpected sorting.

Thank you for your time!

Discussion (0)