How to sort an array of objects by multiple fields?

后端 未结 30 2899
北恋
北恋 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:24

    I like SnowBurnt's approach but it needs a tweak to test for equivalence on city NOT a difference.

    homes.sort(
       function(a,b){
          if (a.city==b.city){
             return (b.price-a.price);
          } else {
             return (a.city-b.city);
          }
       });
    

提交回复
热议问题