From this original question, how would I apply a sort on multiple fields?
Using this slightly adapted structure, how would I sort city (ascending) & then price (
How about this simple solution:
const sortCompareByCityPrice = (a, b) => {
let comparison = 0
// sort by first criteria
if (a.city > b.city) {
comparison = 1
}
else if (a.city < b.city) {
comparison = -1
}
// If still 0 then sort by second criteria descending
if (comparison === 0) {
if (parseInt(a.price) > parseInt(b.price)) {
comparison = -1
}
else if (parseInt(a.price) < parseInt(b.price)) {
comparison = 1
}
}
return comparison
}
Based on this question javascript sort array by multiple (number) fields