This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Case insensitive sorting for string arrays

    Basarat Ali SyedBasarat Ali Syed

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss