gpt4 book ai didi

javascript - 按静态值范围对数组进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:11 25 4
gpt4 key购买 nike

我有一个数组,为了简单起见,我们可以说它是这样的:

var array = [2,55, 22, 6, 7];

我想对其进行排序,我会这样做:

array.sort(function (a, b) {
return b > a ? -1: 1;
});

或者如果我想按升序排序,我会这样做:

array.sort(function (a, b) {
return b < a ? -1: 1;
});

现在,假设我有一个想要排序的值。所以基本上我想按大于数字的值对数组进行排序。所以如果数字是 6,我希望我的数组看起来像这样:

55, 22, 7, 6, 2

但是如果我想在两个数字之间进行排序,比如说 6 和 23,我希望它返回这样的结果:

22, 7, 55, 6, 2

老实说,最后 3 项可以按任何顺序出现,但我排序的范围必须首先出现。

有谁知道我怎样才能实现这一目标。我试过这样:

// Sort our mapped array
mapped.sort(function (a, b) {

// Loop through our properties
for (var i = 0; i < fields.length; i++) {

// Get our value (skip the first)
var field = fields[i],
x = a[field.name],
y = b[field.name];

// If our values are the same, go to the next compare
if (x === y)
continue;

// If we are using greater than
if (field.operator === '>') {

// Check that the value matches our expression
return y < field.expression ? -1 : 1;
}

// If we are using less than
if (field.operator === '<') {

// Check that the value matches our expression
return y > field.expression ? -1 : 1;
}
}
});

field.expression 保存范围值。正如您所看到的,我正在围绕我的字段进行循环,然后尝试排序。

最佳答案

您的比较函数需要检查某个项目是否在范围内,然后将其放在范围之外的项目之前。如果两者都在内部,或者两者都在外部,则必须照常进行比较。

下面的代码可以做到这一点:

var array = [2,55, 22, 6, 7];
var low = 6,
high = 23;
array.sort(function(a, b) {
return ((b >= low && b < high) - (a >= low && a < high)) || (a - b);
});

关于javascript - 按静态值范围对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40119643/

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