按属性值对对象数组进行排序

2022-08-29 21:59:03

我使用AJAX获得了以下对象,并将它们存储在数组中:

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": "5",
        "city": "New York",
        "state": "NY",
        "zip": "00010",
        "price": "962500"
    }
];

如何创建一个函数来仅使用JavaScript按属性以升序降序对对象进行排序?price


答案 1

按价格升序对房屋进行排序:

homes.sort(function(a, b) {
    return parseFloat(a.price) - parseFloat(b.price);
});

或者在ES6版本之后:

homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));

一些文档可以在这里找到。

对于降序,您可以使用

homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));

答案 2

这是一个更灵活的版本,它允许您创建可重用的排序函数,并按任何字段排序。

const sort_by = (field, reverse, primer) => {

  const key = primer ?
    function(x) {
      return primer(x[field])
    } :
    function(x) {
      return x[field]
    };

  reverse = !reverse ? 1 : -1;

  return function(a, b) {
    return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
  }
}


//Now you can sort by any field at will...

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"}];

// Sort by price high to low
console.log(homes.sort(sort_by('price', true, parseInt)));

// Sort by city, case-insensitive, A-Z
console.log(homes.sort(sort_by('city', false, (a) =>  a.toUpperCase()
)));