如何根据键条件按两个键对对象进行排序

时间:2018-11-13 06:07:40

标签: javascript

var obj = 
[{
    "distance": 7000,
    "rating": 2,
    "name": 'a'
},
{
    "distance": 3470,
    "rating": 1,
    "name": 'b'
}, {
    "distance": 3470,
    "rating": 2,
     "name": 'c'
}, {
    "distance": 3480,
    "rating": 5,
    "name": 'd'
}, {
    "distance": 3490,
    "rating": 3,
    "name": 'e'
}, {
    "distance": 4000,
    "rating": 3,
    "name": 'f'
}];

我正在寻找按距离排序的输出,如果距离彼此之间的距离更接近某个值(例如10),然后按 rating 排序。 / p>

我尝试了很多方法,但是没有任何效果。

 obj.sort(function(a, b) {
     return (a["distance"] - b["distance"]);
 });

 obj.sort(function(a, b) {
    return (b["distance"] - a["distance"] <= 10 ? 0: 1) || b["rating"] - 
    a["rating"];
 });

在上面的代码中,我首先尝试按距离排序,然后如果距离差小于10,则按等级排序。 但这不能正常工作。

JSBin链接-https://jsbin.com/nawiderebu/edit?html,js,console

我希望获得如下输出:

[
{
    "distance": 3470,
    "rating": 2,
     "name": 'c'
},{
    "distance": 3470,
    "rating": 1,
    "name": 'b'
}, {
    "distance": 3480,
    "rating": 5,
    "name": 'd'
}, {
    "distance": 3490,
    "rating": 3,
    "name": 'e'
}, {
    "distance": 4000,
    "rating": 3,
    "name": 'f'
},{
    "distance": 7000,
    "rating": 2,
    "name": 'a'
}
]

2 个答案:

答案 0 :(得分:1)

在以下情况下使用Math.abs(a["distance"] - b["distance"] < 10)。您不需要第二次sort通话。

var obj = [
    {
        "distance": 7000,
        "rating": 2,
        "name": 'a'
    },
    {
        "distance": 3470,
        "rating": 1,
        "name": 'b'
    }, {
        "distance": 3470,
        "rating": 2,
         "name": 'c'
    }, {
        "distance": 3480,
        "rating": 5,
        "name": 'd'
    }, {
        "distance": 3490,
        "rating": 3,
        "name": 'e'
    }, {
        "distance": 4000,
        "rating": 3,
        "name": 'f'
    }
]

obj.sort(function(a, b) {
    return Math.abs(a["distance"] - b["distance"]) <= 10 ? (b["rating"] - a["rating"]) : (a["distance"] - b["distance"]);
});

console.log(obj)

答案 1 :(得分:1)

比较结果应返回负,零或正差(根据需要调整20):

var arr = [ { "distance": 7000, "rating": 2, "name": 'a' }, 
            { "distance": 3470, "rating": 1, "name": 'b' }, 
            { "distance": 3470, "rating": 2, "name": 'c' }, 
            { "distance": 3480, "rating": 5, "name": 'd' }, 
            { "distance": 3490, "rating": 3, "name": 'e' }, 
            { "distance": 4000, "rating": 3, "name": 'f' } ]

arr.sort((a, b) => (a.distance - b.distance) / 20 | 0 || b.rating - a.rating)

console.log( JSON.stringify(arr).replace(/},/g, '},\n ') )