A Few Minutes Of Code
A Few Minutes Of Code

    How to sort an array numerically in javascript

    June 14, 2019

    Video Blogger

    image from undraw.co

    To sort an array numerically in javascript you pass a Compare Function to the sort array.

    To Sort lowest to highest

    [1,5,3,9,2,11].sort((a, b) => a - b)
    //outputs [1, 2, 3, 5, 9, 11]

    To Sort highest to lowest swap the a and the b around

    [1,5,3,9,2,11].sort((a, b) => b - a)
    //outputs [11, 9, 5, 3, 2, 1]

    So far so good but what about if our numbers are coming through as a string? The built in compare function will handle this for us.

    ['1','55','3','9','2','11'].sort((a, b) => a - b)
    //outputs ["1", "2", "3", "9", "11", "55"]

    There is also another syntax which you might come across which can be a bit cleaner and reusable.

    const highestToLowest = (a,b) => b - a
    const lowestToLowest = (a,b) => a - b

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

    eg

    console.log([1,5,3,9,2,11].sort(highestToLowest))
    //outputs [11, 9, 5, 3, 2, 1]
    console.log([1,5,3,9,2,11].sort(lowestToLowest))
    //outputs [1, 2, 3, 5, 9, 11]

    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 ascending and descending orders mixed up.

    Categories:
    Previous Create a weather voice assistant in ReactNext How to sort an array alphabetically in javascript