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

更新于: 2020 年 11 月 24 日

1K+ 浏览

开启 职业生涯

完成课程获取认证

开始
广告