Sorting array of objects based on values which are strings in Javascript

Let us assume we have a JSON array of objects that contain some key value pairs. We might want to compare it with similar JSON array to find out whether both are same or not. To do this we might want to sort the array first and then compare as the order of key value pairs might be different.

Lets say we have following json arrays and we want to sort them to compare them.

var json_array1 = [
    {
        "Name" : "Lenovo",
        "Year" : 1985
    },
    {
        "Name" : "HP",
        "Year" : 1986
    },
    {
        "Name" : "HCL",
        "Year" : 1987
    },
    {
        "Name" : "Dell",
        "Year" : 1974
    }
]

var json_array2 = [
    {
        "Name" : "HP",
        "Year" : 1986
    },
    {
        "Name" : "HCL",
        "Year" : 1987
    },
    {
        "Name" : "Lenovo",
        "Year" : 1985
    },
    {
        "Name" : "Dell",
        "Year" : 1974
    }
]

Now to sort them we use the below code to sort them. Notice that we might want to sort it by the Key-Value pair Name.

json_array1.sort((a, b) => {
    let fa = a.Name.toLowerCase(),
        fb = b.Name.toLowerCase();

    if (fa < fb) {
        return -1;
    }
    if (fa > fb) {
        return 1;
    }
    return 0;
});

The above code will return the sorted array of JSON array sorted by the key value pair Name. Notice that we can also sort by using the key value pair Year in that case we don’t need to convert to lowercase since it is a integer type.