TL;DR

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

1. Performance

**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

JS i18n: 5 essential tips for localeCompare() & Intl.Collator()
2.05 GEEK