Sort an array of String with non-ASCII characters.

featured Image

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

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more