In this article we will learn how to sort an array of string with non-ASCII characters.
The Javascript sort()
methods working completely fine when we sort an array ASCII characters in it. However, if you are trying to sort an array of strings with non-ASCII characters like ī, ô in it then the sort()
method wont give you correct results.
Example:
let arrString = ['bee', 'ôrənj', 'tīɡər', 'ant'];
arrString.sort();
console.log(arrString)
//output : [ 'ant', 'bee', 'tīɡər', 'ôrənj' ]
As you can see we got tīɡər before ôrənj’ string which is incorrect sorting of the array.
To solve this issues, we have to use JavaScript localeCompare()
method of string.
The localCompare()
compares two strings in a specific locale. The locale is based upon the language setting of a browser.
Let see this with the example:
let arrString = ['bee', 'ôrənj', 'tīɡər', 'ant'];
arrString.sort((a,b) => {
return a.localeCompare(b)
});
console.log(arrString)
Output:
[ 'ant', 'bee', 'ôrənj', 'tīɡər' ]
Now this output shows the correct order of the string where ôrənj is before tīɡər.