Use the sort() method with function to sort an array of objects by multiple properties in JavaScript. You can combine sorts using the || operator in the order of the sorting we need.
let objs = [
{ name: 'Mark',
age: 30,
RollNo: 'R01'
},
{ name: 'Anne',
age: 20,
RollNo: 'R02'
},
{ name: 'James',
age: 40,
RollNo: 'R03'
},
{ name: 'Jerry',
age: 30,
RollNo: 'R04'
},
{ name: 'Lucy',
age: 30,
RollNo: 'R05'
},
{ name: 'Mark',
age: 30,
RollNo: 'R06'
},
]
objs.sort((a,b)=> (a.age - b.age || a.name.localeCompare(b.name) ));
Changing to Descending order
If we wanted Age and Name to be in descending order we just need to swap the above command with
objs.sort((a,b)=> (b.age - a.age || b.name.localeCompare(a.name) ));
Javascript sorts an array of objects by multiple properties
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
const arr = [
{ id: 1, score: 1, isCut: false, dnf: false },
{ id: 2, score: 2, isCut: false, dnf: false },
{ id: 3, score: 3, isCut: false, dnf: false },
{ id: 4, score: 4, isCut: false, dnf: false },
{ id: 5, score: 5, isCut: true, dnf: true },
{ id: 6, score: 6, isCut: true, dnf: false },
{ id: 7, score: 7, isCut: true, dnf: false },
{ id: 8, score: 8, isCut: true, dnf: false },
{ id: 9, score: 9, isCut: true, dnf: false },
{ id: 10, score: 0, isCut: false, dnf: false },
{ id: 11, score: -1, isCut: false, dnf: false },
{ id: 12, score: -2, isCut: false, dnf: true },
{ id: 13, score: -3, isCut: false, dnf: false },
{ id: 14, score: -4, isCut: false, dnf: false },
{ id: 15, score: -5, isCut: false, dnf: false },
{ id: 16, score: 10, isCut: true, dnf: false }
];
const sortComplex = (arr = []) => {
arr.sort(function (a, b) {
const order = (dnf, isCut) => {
return [0, 1, 3, 2][dnf * 2 + isCut];
}
return order(a.dnf, a.isCut) - order(b.dnf, b.isCut) || b.score - a.score;
});
};
sortComplex(arr);
console.log(arr);
</script>
</body>
</html>
Output:
Sort Array of Objects By Two Properties in JavaScript
homes.sort(
function(a, b) {
if (a.city === b.city) {
// Price is only important when cities are the same
return b.price - a.price;
}
return a.city > b.city ? 1 : -1;
});
Do comment if you have any doubts or suggestions on this JS Array sort topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version