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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more