How to sort an array of objects by multiple fields?

后端 未结 30 2461
北恋
北恋 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条回答
  •  梦如初夏
    2020-11-21 12:20

    You could use a chained sorting approach by taking the delta of values until it reaches a value not equal to zero.

    var data = [{ h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500" }, { h_id: "4", city: "Bevery Hills", state: "CA", zip: "90210", price: "319250" }, { h_id: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];
    
    data.sort(function (a, b) {
        return a.city.localeCompare(b.city) || b.price - a.price;
    });
    
    console.log(data);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Or, using es6, simply:

    data.sort((a, b) => a.city.localeCompare(b.city) || b.price - a.price);
    

提交回复
热议问题