Sorting strings in JavaScript

NicolasBrondinBernard

Author
@NicolasBrondinBernard

When the sort() method acts up with strings in JavaScript!

Article published on 21/02/2022, last updated on 10/08/2026

Having a list of strings and sorting it in alphabetical (or reverse) order in Javascript seems like a rather simple exercise at first glance.

But in reality, it holds its share of complications, and also, a very simple solution to implement.

Let's first look at the problem

Problem

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

/* Tri avec la méthode sort()*/

const arr = ["Chien", "abricot", "électron","résistance", "Tomate"];
const sortedArray = arr.sort();

console.log(sortedArray);
// Fail -> Array(5) [ "Chien", "Tomate", "abricot", "résistance", "électron" ]

If we simply take the first letters of each word in the sorted list "c, t, a, r, é", we already see a problem, but what is the explanation?

Javascript will simply find a mathematical way to sort this list, and choose to look at the ascii table for the numeric value of each letter, and compare them to each other.

In this case, the values of uppercase letters are always smaller (65+) than lowercase ones (97+), and accented letters are much larger (128+).

Solution

Fortunately there is a special method in Javascript for comparing two characters together, taking into account the user's language, and combined with the sort method, we finally arrive at a real alphabetical sort, without any accent or uppercase issues:

/* Tri avec la méthode sort() et localeCompare()*/

const arr = ["Chien", "abricot", "électron","résistance", "Tomate"];
const sortedArray = arr.sort(function (a, b) {
    return a.localeCompare(b);
});

console.log(sortedArray);
// Hourra ! -> Array(5) [ "abricot", "Chien", "électron", "résistance", "Tomate" ]

Finished reading this article?
Our complete courses
Take it to the next level with our courses!

Complete courses, exercises and certificates to really learn programming!

4.8 average rating

Comments (0)

to leave a comment

No comments yet