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.

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay