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!

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.