JavaScript

# How to Sort an Array of Strings in JavaScript?

In this tutorial, we are going to see How to Sort an Array of Strings in JavaScript?

Having a list of strings and sorting them in alphabetical order (or the opposite) in Javascript seems to be a rather simple exercise at first sight.

But in fact, it contains some complications, and also, a way very simple to achieve.

###### Problem:

Here is a simple example of using the .sort() method on an array of strings, which gives… strange results:

```/* Sorting with the sort() method */

const arr = ["yellow", "black", "White","red", "green"];
const res = arr.sort();

console.log(res);```

Output:

`["White", "black", "green", "red", "yellow"]`

If we simply take the first letters of each word in the sorted list “w, b, g, r, y”, we already see a problem, but what is the reason?
Javascript will simply find a mathematical way to sort this list and choose to look at the numerical value of each letter in the ASCII table and compare them.

In this case, the values of uppercase letters are always smaller (65+) than lowercase letters (97+).

###### Solution:

Fortunately, there is a special method in Javascript to compare two characters together, considering the language of the user, and coupled with the sort method, we finally get a real sorting by alphabetical order, without capitalization problem:

```/* Sorting with the sort() and localeCompare() method */

const arr = ["yellow", "black", "White","red", "green"];
const res = arr.sort(function (a, b) {
return a.localeCompare(b);
});

console.log(res);```

Output:

`["black", "green", "red", "White", "yellow"]`

MCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More