DEV Community

Jesse M. Holmes
Jesse M. Holmes

Posted on

3 2

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay