How to sort an array of objects by multiple fields?

后端 未结 30 2871
北恋
北恋 2020-11-21 11:34

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 (

30条回答
  •  Happy的楠姐
    2020-11-21 12:04

    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.
    • Subtraction works on numeric fields.
    • || in the last line gives city priority over price.
    • Negate to reverse order in any field, as in -price_order
    • Date comparison, var date_order = new Date(left.date) - new Date(right.date); works like numerics because date math turns into milliseconds since 1970.
    • Add fields into the or-chain, return city_order || -price_order || date_order;

提交回复
热议问题