Case insensitive sorting for string arrays

Share this video with your friends

Social Share Links

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.

[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.