根据{liked:true},距离然后通过avg_rating进行多重排序数组对象

时间:2019-07-05 07:08:16

标签: javascript node.js sorting

我有一个如下的对象数组

arr = [ {distance:4, avg_rating: 5}, 
        {distance: 6, avg_rating: 4}, 
        {distance: 7, avg_rating: 2, liked: true}, 
        {distance: 6, avg_rating: 4 , liked: true}, 
        {distance: 6, avg_rating: 3 , liked: true},
        {distance: 4, avg_rating: 3}]

我希望首先得到{liked:true},然后按照距离升序对其进行排序,如果距离相同,则将根据avg_rating对其进行排序。

我使用了无法正常工作的javascript排序方法。

arr.sort(function(a, b){                                     
      if (b.liked)  return  1;
      if(!b.liked) return -1;
      if (a.distance < b.distance) return 1;
      if (a.distance > b.distance) return -1;
      if (a.avg_rating < b.avg_rating) return -1;
      if (a.avg_rating > b.avg_rating) return 1;
 })

我希望结果是

arr = [{distance: 6, avg_rating: 4 , liked: true},
       {distance: 6, avg_rating: 3 , liked: true}
       {distance: 7, avg_rating: 2, liked: true},
       {distance: 4, avg_rating: 5},
       {distance: 4, avg_rating: 3},
       {distance: 6, avg_rating: 4}]

因此,首先所有{likes:true}都在顶部,并按距离升序排序(即所有附近都在数组顶部),然后,如果距离相同,则按avg_rating降序排序(即都相同距离值再次通过avg_rating排序)

1 个答案:

答案 0 :(得分:1)

您可以链接所有条件并通过获取每个项目的差额来获取所需的订单。

对于第一对,请使用logical NOT !以获得布尔值以进行减法。

其他的则按排序顺序a - b(asc)和b - a(desc)进行排序。

var array = [{ distance: 4, avg_rating: 5 }, { distance: 6, avg_rating: 4 }, { distance: 7, avg_rating: 2, liked: true }, { distance: 6, avg_rating: 4, liked: true }, { distance: 6, avg_rating: 3, liked: true }, { distance: 4, avg_rating: 3 }];

array.sort((a, b) =>
    !a.liked - !b.liked ||
     a.distance - b.distance ||
     b.avg_rating - a.avg_rating
);

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