排序一组JavaScript对象

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

如何创建一个函数来按price属性按升序降序排序对象,只使用JavaScript?


按照价格从小到大排序:

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

或者在ES6版本之后:

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

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


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

var sort_by = function(field, reverse, primer){

   var 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));
     } 
}

现在你可以按任意字段排序......

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"

}];

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

// Sort by city, case-insensitive, A-Z
homes.sort(sort_by('city', false, function(a){return a.toUpperCase()}));

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

// 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);

如果要按升序切换减号每一侧的表达式。

链接地址: http://www.djcxy.com/p/3235.html

上一篇: Sorting an array of JavaScript objects

下一篇: How to sort an array of objects by multiple fields?