开发者问题收集

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

2009-06-11
1589076

我使用 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 属性以 升序 降序 顺序对对象进行排序?

3个回答

按价格升序排列房屋:

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));
Stobor
2009-06-11

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

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()
)));
Kenan Banks
2009-06-11

要对其进行排序,您需要创建一个采用两个参数的比较函数。然后使用该比较函数调用排序函数,如下所示:

// a and b are object elements of your array
function mycomparator(a,b) {
  return parseInt(a.price, 10) - parseInt(b.price, 10);
}
homes.sort(mycomparator);

如果要按升序排序,请切换减号两侧的表达式。

Ricardo Marimon
2009-06-11