gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:26:02 26 4
gpt4 key购买 nike

我有一个如下所示的数组对象

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}]

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

最佳答案

您可以链接所有条件并通过获取每个项目的增量来获得想要的订单。

对于第一对,取 logical NOT !获取用于减法的 bool 值。

其他的按照排序的顺序取,a - b (asc) and 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; }

关于javascript - 根据{喜欢的:true} ,距离然后通过avg_rating对数组对象进行多重排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56898156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com