JavaScript native sort method does not work for most of foreign language, which has non-ASCII characters like [‘ą’, ‘ㄱ’, ‘世’, ‘д’, ‘e’]
['Poland', 'Germany', 'France', 'Russia', 'Japan'].sort();
// ["France", "Germany", "Japan", "Poland", "Russia"] GOOD
['Hängt', 'Haut', 'Hüllen', 'Hubert'].sort();
// ["Haut", "Hubert", "Hängt", "Hüllen"] BAD
Quick Solution
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
**Intl.Collator**
** is better performer than ****localeCompare**
Intl.Collator
Object and its compare
property is better than localeCompare()
in terms of performance for comparing large number of strings
localeCompare()
const a = 'réservé'; // with accents, lowercase
const b = 'RESERVE'; // no accents, uppercase
console.log(a.localeCompare(b));
// expected output: 1
Intl.Collator()
const a = 'réservé'; // with accents, lowercase
const b = 'RESERVE'; // no accents, uppercase
console.log(new Intl.Collator().compare(a, b));
// expected output: 1
#coding #web-development #tips #programming #javascript