How to sort an array of object by two fields in JavaScript ?

We have given an array of objects and the task is to sort the array of elements by 2 fields of the object. There are two methods to solve this problem which are discussed below:Â
Approach 1:
- First compare the first property, if both are unequal then sort accordingly.
- If they are equal then do the same for the second property.
Example: This example implements the above approach with a custom comparison function.Â
Javascript
// Create an array of objectslet arr = [    { first: 3, second: 4 },    { first: 3, second: 1 },    { first: 1, second: 10 }];Â
// Apply array.sort with comparison functionarr.sort(function (a, b) {Â Â Â Â let af = a.first;Â Â Â Â let bf = b.first;Â Â Â Â let as = a.second;Â Â Â Â let bs = b.second;Â
    // If first value is same    if (af == bf) {        return (as < bs) ? -1 : (as > bs) ? 1 : 0;    } else {        return (af < bf) ? -1 : 1;    }});Â
// Display outputconsole.log("'" + JSON.stringify(arr[0])Â Â Â Â + ", " + JSON.stringify(arr[1]) + ", "Â Â Â Â + JSON.stringify(arr[2]) + "'"); |
Output
'{"first":1,"second":10}, {"first":3,"second":1}, {"first":3,"second":4}'
Approach 2:
- First compare the first property, If both are unequal then sort accordingly.
- If they are equal then do the same for the second property, this example is following the same approach but uses OR Gate to reduce the code.
Example: This example implements the above approach with a custom comparison function.Â
Javascript
// Create input array of objectslet arr = [    { first: 3, second: 4 },    { first: 3, second: 1 },    { first: 1, second: 10 }];Â
// Apply array.sort with custom comparision funtionarr.sort(function (a, b) {         // Compare first value then second     return a.first - b.first || a.second - b.second;});Â
// Display the outputconsole.log("'" + JSON.stringify(arr[0])Â Â Â Â + ", " + JSON.stringify(arr[1]) + ", "Â Â Â Â + JSON.stringify(arr[2]) + "'"); |
Output
'{"first":1,"second":10}, {"first":3,"second":1}, {"first":3,"second":4}'
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



