DEV Community

Krzysztof Żuraw
Krzysztof Żuraw

Posted on • Originally published at krzysztofzuraw.com on

Intl Collator in JavaScript

Recently I needed to sort an array of objects from A to Z. Usually for such task I’m using the following piece of code:

const cities = [{ name: 'Wrocław' }, { name: 'Kraków' }, { name: 'Łódź' }];

cities.sort((city1, city2) => (city1.name > city2.name ? 1 : -1));
Enter fullscreen mode Exit fullscreen mode

Yet I had a problem with this code - the last city Łódź was not in the right place. The proper order should be:

[{ name: 'Kraków' }, { name: 'Łódź' }, { name: 'Wrocław' }];
Enter fullscreen mode Exit fullscreen mode

But code from previous example returned:

[{ name: 'Kraków' }, { name: 'Wrocław' }, { name: 'Łódź' }];
Enter fullscreen mode Exit fullscreen mode

Why is that? Because Łódź is not starting from Unicode character - it is a utf-8 one.

How then can I sort an array with utf-8 characters? In turns out that all major browsers have support for localeCompare.

What it is? I like to think about this method as a way of sorting with utf-8 support. localeCompareallows me to compare two strings with internationalization support. My sorting example now can be changed to:

const cities = [{ name: 'Wrocław' }, { name: 'Kraków' }, { name: 'Łódź' }];

cities.sort((city1, city2) => city1.name.localeCompare(city2.name));
// [{name: 'Kraków'},{name: 'Łódź'},{name: 'Wrocław'}];
Enter fullscreen mode Exit fullscreen mode

There is a lot of configuration options to localeCompate - if you want to know more I recommend visiting mdn.

Summary

In this blog post, I wrote on how to use localeCompareto sort strings that are utf-8.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)