物件陣列的多字段排序
如果需要根據物件陣列中的多個欄位進行排序,可以使用鍊式排序可以採用的方法。此方法涉及按順序比較每個欄位的值,直到獲得非零差異。
實作
考慮下列物件陣列:
var homes = [ {"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"} ];
要依照城市(升序)和價格(降序)對此數組進行排序,請使用以下排序function:
data.sort(function (a, b) { return a.city.localeCompare(b.city) || b.price - a.price; });
說明
說明如果a.city.localeCompare(b.city) 等於 0,b.price - a.price 用來比較價格。正值將 b 置於 a 之前,負值將 a 置於 b 之前。
範例輸出[{ "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500" }, { "h_id": "6", "city": "Dallas", "state": "TX", "zip": "75000", "price": "556699" }, { "h_id": "4", "city": "Bevery Hills", "state": "CA", "zip": "90210", "price": "319250" }, { "h_id": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500" }]排序後,homes 陣列重新排列如下:
以上是如何在 JavaScript 中使用多個欄位對物件陣列進行排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!