DEV Community

Jesse M. Holmes
Jesse M. Holmes

Posted on

Sorting Strings in JavaScript with localCompare

Take this list of strings:

let names = ['Lyra', 'Iorek', 'pantalaimon', 'Asriel', 'Serafina']
Enter fullscreen mode Exit fullscreen mode

We want to sort it alphabetically. Naturally, we can check the MDN for Array.prototype.sort(), and we find that names.sort() will do the job pain-free.

A week after you've submitted your work, a ticket is opened and assigned to you: Users are complaining that their names aren't in the correct order

After taking a look, you see that Lee has submitted his name in lowercase. Of course he did.

let names = ['Lyra', 'Iorek', 'pantalaimon', 'Asriel', 'Serafina', 'lee']
console.log(names.sort())
// Result ['Asriel', 'Iorek', 'Lyra', 'Serafina', 'lee', 'pantalaimon']
Enter fullscreen mode Exit fullscreen mode

As you can see, users with lowercase names are sorted at the end. They're in order by themselves, but Product may not get your sense of humor when you explain it to them.

The reason lower case names are at the end has to do with their ASCII values. If you check the chart, you'll see that lowercase letters have larger numerical ASCII values. Time to google javascript sort strings ignore case

Now we've been introduced to a new method, localeCompare. This method is packed with options that are available in all modern browsers. Check the usage chart at the bottom of the MDN page—some mobile browsers don't have full support for the options.

Here's the finished sort:

let names = ['Lyra', 'Iorek', 'pantalaimon', 'Asriel', 'Serafina', 'lee']
console.log(names.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base'})))
// result: ['Asriel', 'Iorek', 'lee', 'Lyra', 'pantalaimon', 'Serafina']
Enter fullscreen mode Exit fullscreen mode

Top comments (0)