Case insensitive sorting for string arrays

Share this video with your friends

Send Tweet

We look at the default Array.prototype.sort behavior and discuss how you can do case insensitive string sorting. This isn’t as straightforward as it seems, Javascript by default sorts capitalized words before lowercase. In this lesson we’ll learn exactly how to deal with this behavior using TypeScript.

RagIb Hasan
RagIb Hasan
~ 7 years ago

Can we use

foo.sort((a, b) => a.toLocaleLowerCase(b));

instead of

foo.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase));

?

Chris Villanueva
Chris Villanueva
~ 7 years ago

@Raglb I tried your suggestion in nodejs. It didn't work as expected.

Ind. Puking Rainbows
Ind. Puking Rainbows
~ 3 years ago

const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' }); arrayOfObjects.sort((a, b) => { return collator.compare(a.name, b.name); });