How to sort an array of objects by multiple fields? code example
Example 1: sort array of objects by 2 key value
homes.sort(
function(a, b) {
if (a.city === b.city) {
return b.price - a.price;
}
return a.city > b.city ? 1 : -1;
});
Example 2: javascript sort array of objects multiple fields
array.sort(function(a,b){
let i = 0, result = 0;
while(i < sortBy.length && result === 0) {
result = sortBy[i].direction*(a[ sortBy[i].prop ].toString() < b[ sortBy[i].prop ].toString() ? -1 : (a[ sortBy[i].prop ].toString() > b[ sortBy[i].prop ].toString() ? 1 : 0));
i++;
}
return result;
})