Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 1046 of the free egghead.io lessons, plus get TypeScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Case insensitive sorting for string arrays

1:33 TypeScript lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

We look at the default Array.prototype.sort behavior and discuss how you can do case insensitive string sorting.

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.

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.

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?