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 (
Here's an extensible way to sort by multiple fields.
homes.sort(function(left, right) {
var city_order = left.city.localeCompare(right.city);
var price_order = parseInt(left.price) - parseInt(right.price);
return city_order || -price_order;
});
Notes
a.localeCompare(b)
is universally supported and returns -1,0,1 if a,a==b
,a>b
respectively.
||
in the last line gives city
priority over price
.-price_order
var date_order = new Date(left.date) - new Date(right.date);
works like numerics because date math turns into milliseconds since 1970.return city_order || -price_order || date_order;