A Few Minutes Of Code
A Few Minutes Of Code

    How to sort an array alphabetically in javascript

    June 14, 2019

    Video Blogger

    image from undraw.co

    To sort an array alphabetically in javascript you can use the sort function.

    To Sort a-z.

    //outputs ["blue", "green", "purple", "red", "yellow"]

    This works well but what if there is a mix between lower case and uppercase? eg

    //outputs ["Green", "Silver", "blue", "green", "purple", "red", "yellow"]

    Despite what you might expect the sort method sorts alphabetically but has the capitalised letters words before the lowercase letters.

    A more robust solution which will also handle non standard letters such as é is to use the localeCompare.

    So now

    //outputs ["blue", "green", "Green", "purple", "red", "Silver", "yellow"]

    As discussed in our article on sorting numerically there is also another syntax which you might come across which can be a bit cleaner and reusable.

    const sortAtoZ = (a,b)=>a.localeCompare(b)
    const sortZtoA = (a,b)=>b.localeCompare(a)

    This will allow us to pass in our function directly into the sort.


    //outputs ["blue", "green", "Green", "purple", "red", "Silver", "yellow"]
    //outputs ["yellow", "Silver", "red", "purple", "Green", "green", "blue"]

    I find this the best solution because we are able to test this function and reuse it with confidence across our codebase, also by giving a descriptive name to the function we help prevent getting our orders mixed up.

    Previous How to sort an array numerically in javascriptNext How to sort an array of objects in javascript