Explain Codes LogoExplain Codes Logo

How to sort strings in JavaScript

javascript
sort-function
locale-compare
javascript-best-practices
Nikita BarsukovbyNikita Barsukov·Nov 2, 2024
TLDR

Eager to sort an array of strings in JavaScript? Use the sort() method, simple as this:

let fruits = ['Banana', 'apple', 'Orange']; fruits.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })); console.log(fruits); // ['apple', 'Banana', 'Orange']

The localeCompare() function resorts to case-insensitive sorting and treats special characters like ordinary ones. Applying the { sensitivity: 'base' } option sets a solid base for consistency across various environments.

Foolproof string sorting

When you're sorting strings, it's better to be safe than sorry. Ensure that the elements to sort are indeed strings:

let items = [{name: 'Banana'}, {name: 'apple'}, {name: 'Orange'}]; items.sort((a, b) => ('' + a.name).localeCompare('' + b.name)); console.log(items.map(item => item.name)); // ['apple', 'Banana', 'Orange']

With a simple trick of appending an empty string to a.name and b.name, we eliminate the risk of misinterpreted data types.

Advanced sorting scenarios

Tackling special characters and locale differences

When you come across some äpples among your apples or need to follow certain locale-specific sorting rules, you can flexibly specify locale and other options:

let words = ['ä', 'a', 'z']; words.sort((a, b) => a.localeCompare(b, 'de', { sensitivity: 'base' })); console.log(words); // ['a', 'ä', 'z'] // Germans love their details sorted.

Sorting with multiple attributes

It's like sorting Hogwarts students by houses. And within the same house, by their names:

let students = [{house: 'Gryffindor', name: 'Harry'}, {house: 'Slytherin', name: 'Draco'}, {house: 'Gryffindor', name: 'Neville'}]; students.sort((a, b) => { let houseComparison = a.house.localeCompare(b.house); return houseComparison !== 0 ? houseComparison : a.name.localeCompare(b.name); }); console.log(students); // Because we all know Hogwarts wasn't sorted by a JavaScript algorithm. 😉

Exception-proof sorting

In production-grade code, exceptions can turn into bugs. That's why they should be caught and addressed:

try { fruits.sort((a, b) => a.localeCompare(b)); } catch (e) { console.error('Sorting error:', e); // Oh no! An apple sneaked into our bananas again ! }

Advanced nuances and potential pitfalls

Consistency across browsers

Even though localeCompare() provides a cornucopia of functionalities and has good compatibility, slight uncertainties persist across browsers due to different Unicode collation algorithms. If you're a stickler for consistency, dive into custom collation functions or explore third-party libraries.

Efficiency issues

Sure, arrow functions and localeCompare() score high on compactness and efficiency. Yet, if you're dealing with the Atlantic Ocean size dataset, or just can't afford any performance slip, it's not a bad idea to benchmark and seek out faster sort implementations.

Corner cases and characters

When you encounter a horde of Unicode characters beyond the usual ASCII characters, dredge up custom sorting logic. Oh, and pro tip: storing values in variables within the sort function makes future you or your fellow coders' life easier when debugging!

Best practices

Last but not least, always cast your values to strings, use semicolons like they're going out of fashion, and pay attention to the proper syntax of your sort function. The bug bites in the details!