Case insensitive sorting for string arrays

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 2 years ago

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.

[00:01] Here, we have an array, foo, of a few strings. The strings contain mixed case, for example Alpha with a capital A, beta with a small B, gamma with a capital G, and delta with a small D. By default, if I call the sort method on this array and log out the sorted array, you will see that all the capital words appear before the lowercase ones.

[00:31] Alpha and Gamma are before beta and delta. This is because the default string sorting in JavaScript is case-sensitive, and capital-case strings come before lowercase strings in the Unicode code points. Capital G will come before lowercase B and D.

[00:50] To do case-insensitive sorting, we need to provide a custom compare function to array prototype sort. We simply use a function that takes two strings, and uses the localeCompare function of the first string to compare the string to the second one, and return it.

[01:10] Now, there are a few ways of ways adding case-insensitivity to this, but the simplest one with the greatest browser support is to simply convert both strings to lowercase before comparing them using localeCompare. Now, if we run the code, you can see that the strings are compared case-insensitively.

RagIb Hasan
RagIb Hasan
~ 6 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
~ 5 years ago

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

Ind. Puking Rainbows
Ind. Puking Rainbows
~ 2 years ago

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