在 JavaScript 中按價格對陣列進行排序
假設我們有一個物件陣列,其中包含有關房屋和價格這樣的資料——
const arr = [ { "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": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500" } ];
我們要求編寫一個 JavaScript 函式來接受這樣一個數組。該函式應根據物件的 price 屬性(目前為字串)對陣列進行排序(按升序或降序)。
示例
對應的程式碼如下——
const arr = [ { "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": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500" } ]; const eitherSort = (arr = []) => { const sorter = (a, b) => { return +a.price - +b.price; }; arr.sort(sorter); }; eitherSort(arr); console.log(arr);
輸出
而在控制檯的輸出為——
[ { 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: '5', city: 'New York', state: 'NY', zip: '00010', price: '962500' } ]
廣告