Sort an array of String with non-ASCII characters.
This article is how to sort an array of string with non-ASCII characters. Using localeCompare() we can sort mixed array with non-ascii characters.
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.
Related Posts
Capitalize First Letter of a String - JavaScript
This article is about how to capitalize the first letter of a string using JavaScript.
Check if String starts with a space in JavaScript
Find out whether a string starts with a space or not using regex test method, string match method and startsWith method in JavaScript.
JavaScript - Detect if a string contains any space
FInd out how to detect if a string contains any white space using regex test() method and string indexOf() method in Javascript.
Split a String into chunks of N character into an array in JavaScript
Find out how to split String into Substrings by length of N characters in JavaScript using split(), match() and substr() methods.
