gpt4 book ai didi

javascript - 对具有两个以上状态的数组进行排序

转载 作者:行者123 更新时间:2023-12-03 06:45:54 25 4
gpt4 key购买 nike

我尝试对数组进行排序,但输出不是我想要的。

我有一个像这样的数组:

var myArray = [
{
...
"foo": false,
"bar": true,
...
},
{
...
"foo": true,
"bar": false,
...
},
{
...
"foo": true,
"bar": false,
...
},
{
...
"foo": false,
"bar": false,
...
},
...
];

我想以这种方式对这个数组进行排序

myArray.sort(function(a,b) {
var foo = a.foo;
var bar = b.bar;

if(foo === false && bar === true) {
// this should sort on top
return -1;
}

if(foo === false && bar === false) {
// this should sort as second
return 0;
}

if(foo === true && bar === true) {
// this should sort as third
return 0;
}

if(foo === true && bar === false) {
// this should sort as last
return 1;
}
});

我认为 sort 函数存在逻辑问题。

我想要的输出是我在 if 注释中为你注释它

最佳答案

您可以根据现有条件为数组对象添加权重属性。喜欢

var tempArr = myArray.map(function(obj) {
var foo = obj.foo;
var bar = obj.bar;

if (foo === false && bar === true) {
// this should sort on top
obj.weightage = 1;
}

if (foo === false && bar === false) {
// this should sort as second
obj.weightage = 2;
}

if (foo === true && bar === true) {
// this should sort as third
obj.weightage = 3;
}

if (foo === true && bar === false) {
// this should sort as last
obj.weightage = 4;
}

return obj;
});

然后对数组使用排序函数

tempArr = tempArr.sort(function(a, b) {
return a.weightage - b.weightage;
});

关于javascript - 对具有两个以上状态的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37738403/

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