Explain Codes LogoExplain Codes Logo

Sort array by firstname (alphabetically) in JavaScript

javascript
sorting
localecompare
array-methods
Anton ShumikhinbyAnton Shumikhin·Aug 13, 2024
TLDR

Crunch the data faster by using sort with localeCompare to sort an array by firstname in alphabetical order.

const humans = [{ firstname: 'John' }, { firstname: 'Jane' }]; humans.sort((a, b) => a.firstname.localeCompare(b.firstname));

This coffee-break-friendly code snippet sorts your array typically before you sip the first gulp. It uses localeCompare to achieve sharp alphabetical comparison.

Breaking down sort and localeCompare

Between sort & localeCompare, who does what? Let's nail this!

Meet Mr. sort

sort is a method that loves juggling elements in an array. When paired with localeCompare, it sorts strings like a pro, considering local extra-terrestrial alphabets.

High five to localeCompare

localeCompare accepts the challenge to compare strings based on the local language settings. It easily handles accents, curvy umlauts, and case sensitivity. Flaunt with { sensitivity: 'base' } option for customized comparison:

humans.sort((a, b) => a.firstname.localeCompare(b.firstname, 'en', { sensitivity: 'base' }));

Can't confuse 'Álvaro' with 'Alvaro' anymore. Thanks to localeCompare, they are twin names in alphabet land now.

Upping the game with advanced sorting

localeCompare fits most gloves but we have more to the party when you need to tailor-make your sorting logic!

Ignoring case while sorting

Force firstname to lowercase for a uniform case comparison.

humans.sort((a, b) => a.firstname.toLowerCase().localeCompare(b.firstname.toLowerCase()) ); // Remember Jane, john is not taller than you. He's just uppercase

Maintaining, the Originality

Retain the original order if firstnames match. Return 0.

humans.sort((a, b) => { const nameA = a.firstname.toLowerCase(); const nameB = b.firstname.toLowerCase(); // In case of a tie, respect original ordering. Fair play! return nameA === nameB ? 0 : nameA < nameB ? -1 : 1; });

What? Still, a tie?

Sort by firstname and then by another field if firstnames are identical for the tiebreaker.

humans.sort((a, b) => { const nameCompare = a.firstname.localeCompare(b.firstname); // If names match, let lastname cast the deciding vote return nameCompare !== 0 ? nameCompare : a.lastname.localeCompare(b.lastname); });

Pro tips and Common Pitfalls

A few words of wisdom for you. Including tips to avoid stepping on nasty sorting pitfalls:

Nobody likes slowpokes

Large arrays could give tortoise-like performance during sorting. Race ahead by pre-processing data.

Mind the Gap

Ensure property names are not only present but are also uniformly cased. To balance the risk use the ?? operator to prevent errors when your firstname might be undefined or null. To err is human, to prevent is developer.

Internationalization is cool, but...

localeCompare could be influenced by user locale settings. Remember to test your code for consistency and correctness. When in Rome, code like the Romans!