How to sort an array of objects by multiple fields?

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

    for a non-generic, simple solution to your exact problem:

    homes.sort(
       function(a, b) {          
          if (a.city === b.city) {
             // Price is only important when cities are the same
             return b.price - a.price;
          }
          return a.city > b.city ? 1 : -1;
       });
    

提交回复
热议问题