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"] |
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 |
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 |
Using Intl.Collator()
['Hängt', 'Haut', 'Hüllen', 'Hubert'].sort(Intl.Collator().compare); | |
//["Hängt", "Haut", "Hubert", "Hüllen"] Good |
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)