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

1

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.

['Poland', 'Germany', 'France', 'Russia', 'Japan'].sort();
// ["France", "Germany", "Japan", "Poland", "Russia"]
view raw sort.js hosted with ❤ by GitHub

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.

['Hängt', 'Haut', 'Hüllen', 'Hubert'].sort();
// ["Haut", "Hubert", "Hängt", "Hüllen"] Bad
view raw sort-compare.js hosted with ❤ by GitHub

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

Using localeCompare()

['Hängt', 'Haut', 'Hüllen', 'Hubert'].sort(function (a, b) {
return a.localeCompare(b);
});
//["Hängt", "Haut", "Hubert", "Hüllen"] Good
view raw localcompare.js hosted with ❤ by GitHub

Using Intl.Collator()

['Hängt', 'Haut', 'Hüllen', 'Hubert'].sort(Intl.Collator().compare);
//["Hängt", "Haut", "Hubert", "Hüllen"] Good
view raw intlcollator.js hosted with ❤ by GitHub

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!

Image of Bright Data

Global Data Access Unlocked – Reach data across borders without restrictions.

Unlock the power of global data collection with our advanced proxy solutions. Ideal for market research and more.

Unlock Data Now

Top comments (0)

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay