Code Snippet: How to Sort An Array of JSON Objects By Property

While working on another project, I ran into a situation where I needed to sort an array of JSON objects. Now, for those of you who may be new to JavaScript, the array.sort method allows you to pass in a custom sort function that is meant to look something like this:

array.sort(function (a, b) {
    var sortStatus = 0;

    if (a < b) {
        sortStatus = -1;
    } else if (a > b) {
            sortStatus = 1;
    }

    return sortStatus;
});

Basically, the function takes in two values (a and b), compares them, and then returns the appropriate numeric code. Given the nature of JSON objects, this basic approach won’t work. We could, however, create a function for each property we want to sort by. For example, let’s say we wanted to sort by the firstName property:

function sortByFirstName(a, b) {
    var sortStatus = 0;

    if (a.firstName < b.firstName) {
        sortStatus = -1;
    } else if (a.firstName > b.firstName) {
            sortStatus = 1;
    }
    return sortStatus;
}

array.sort(sortByFirstName);

Now, while this approach works just fine, it doesn’t really scale. If each of the JSON objects being sorted has dozens of properties, you would need to create dozens of methods. However, there is a better approach:

function sortByProperty(property) {
    'use strict';
    return function (a, b) {
        var sortStatus = 0;
        if (a[property] < b[property]) {
            sortStatus = -1;
        } else if (a[property] > b[property]) {
            sortStatus = 1;
        }

        return sortStatus;
    };
}

array.sort(sortByProperty('firstName'));

Here we’re using the sortByProperty method to dynamically generate the sorting method we saw earlier. This way, you can use a single method to sort any the array against any property you want.