在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' } ]