小编典典

如何按多个字段对对象数组进行排序?

all

使用这种稍微调整的结构,我将如何对城市(升序)和价格(降序)进行排序?

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":"6",
     "city":"Dallas",
     "state":"TX",
     "zip":"75000",
     "price":"556699"},
    {"h_id":"5",
     "city":"New York",
     "state":"NY",
     "zip":"00010",
     "price":"962500"}
    ];

我喜欢这个事实,而不是给出了一个提供一般方法的答案。在我计划使用此代码的地方,我将不得不对日期和其他事情进行排序。“启动”对象的能力似乎很方便,如果不是有点麻烦的话。

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

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

我试图将这个答案构建成一个很好的通用示例,但我运气不佳。

这是对具有多列的对象数组进行排序的通用方法:

var arr = [
    { id:5, name:"Name3" },
    { id:4, name:"Name1" },
    { id:6, name:"Name2" },
    { id:3, name:"Name2" }
],

// generic comparison function
cmp = function(x, y){
    return x > y ? 1 : x < y ? -1 : 0; 
};

//sort name ascending then id descending
arr.sort(function(a, b){
    //note the minus before -cmp, for descending order
    return cmp( 
        [cmp(a.name, b.name), -cmp(a.id, b.id)], 
        [cmp(b.name, a.name), -cmp(b.id, a.id)]
    );
});

要添加其他列进行排序,您可以在数组比较中添加其他项目。

arr.sort(function(a, b){
    return cmp( 
        [cmp(a.name, b.name), -cmp(a.id, b.id), cmp(a.other, b.other), ...], 
        [cmp(b.name, a.name), -cmp(b.id, a.id), cmp(b.other, a.other), ...]
    );
});

编辑:根据下面的@PhilipZ 评论,JS 中的数组比较将它们转换为用逗号分隔的字符串。


阅读 80

收藏
2022-05-05

共1个答案

小编典典

您可以使用链式排序方法,获取值的增量,直到它达到不等于零的值。

var data = [{ 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: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];



data.sort(function (a, b) {

    return a.city.localeCompare(b.city) || b.price - a.price;

});



console.log(data);


.as-console-wrapper { max-height: 100% !important; top: 0; }

或者,使用 es6,简单地:

data.sort((a, b) => a.city.localeCompare(b.city) || b.price - a.price);
2022-05-05