How to sort an array of object by two fields in JavaScript ?
Last Updated :
26 Jun, 2024
Improve
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.
// Create an array of objects
let arr = [
{ first: 3, second: 4 },
{ first: 3, second: 1 },
{ first: 1, second: 10 }
];
// Apply array.sort with comparison function
arr.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 output
console.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.
// Create input array of objects
let arr = [
{ first: 3, second: 4 },
{ first: 3, second: 1 },
{ first: 1, second: 10 }
];
// Apply array.sort with custom comparision funtion
arr.sort(function (a, b) {
// Compare first value then second
return a.first - b.first || a.second - b.second;
});
// Display the output
console.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 3: Using a Dynamic Comparison Function
In this approach, we create a dynamic comparison function that accepts the properties to sort by as parameters. This makes the function reusable for different sets of properties without hardcoding the property names.
function dynamicSort(properties) {
return function(a, b) {
for (let i = 0; i < properties.length; i++) {
let prop = properties[i];
if (a[prop] < b[prop]) return -1;
if (a[prop] > b[prop]) return 1;
}
return 0;
}
}
const data = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 22 },
{ name: 'John', age: 22 },
{ name: 'Jane', age: 25 }
];
const sortedData = data.sort(dynamicSort(['name', 'age']));
console.log(sortedData);
Output
[ { name: 'Jane', age: 22 }, { name: 'Jane', age: 25 }, { name: 'John', age: 22 }, { name: 'John', age: 25 } ]