按属性值对对象数组进行排序 - JavaScript
假设我们有一个这样的对象数组 −
const 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": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500" } ];
我们需要编写一个 JavaScript 函数,按 price 属性从升序或降序对对象进行排序。
示例
以下是代码 −
const 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": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500" } ]; const sortByPrice = arr => { arr.sort((a, b) => { return parseFloat(a.price) - parseFloat(b.price); }); }; sortByPrice(homes); console.log(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: '5', city: 'New York', state: 'NY', zip: '00010', price: '962500' } ]
广告