gpt4 book ai didi

javascript - jquery/javascript 中的自定义排序方法

转载 作者:行者123 更新时间:2023-12-01 02:05:04 26 4
gpt4 key购买 nike

我想以自定义方式对数组进行排序

给定数组:

arry = [0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,21,21,22,22,23,23]

预期输出:

[21,22,22,23,23,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18]

最佳答案

您可以先检查该值,然后先检查大于20的排序号。

var array = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 21, 21, 22, 22, 23, 23],
predicate = function (v) { return v > 20; };

array.sort(function(a, b) {
return predicate(b) - predicate(a) || a - b;
});

console.log(array);

关于javascript - jquery/javascript 中的自定义排序方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42436049/

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