gpt4 book ai didi

javascript - 对对象数组中的嵌套数组进行排序

转载 作者:行者123 更新时间:2023-11-28 18:34:13 25 4
gpt4 key购买 nike

我不知道为什么,但排序是编程中每次都让我困惑的事情之一......

我想在第一级对数组成员进行排序,以便所有具有属性 licence: "truck"和 active: true 的成员首先出现在列表中。那么下一个成员应该是所有拥有许可证:“汽车”且活跃:true

的成员

underscore.js 可用...

[
{
name: 'Denes',
properties: [
{
licence: "car",
active: true
},
{
licence: "truck",
active: false
},
]
},
{
name: 'Patrick',
properties: [
{
licence: "car",
active: false
},
{
licence: "truck",
active: true
},
]
},
{
name: 'Marc',
properties: [
{
licence: "car",
active: false
},
{
licence: "truck",
active: false
},
]
}
]

预期结果:

[

{
name: 'Patrick',
properties: [
{
licence: "car",
active: false
},
{
licence: "truck",
active: true
},
]
},
{
name: 'Denes',
properties: [
{
licence: "car",
active: true
},
{
licence: "truck",
active: false
},
]
},
{
name: 'Marc',
properties: [
{
licence: "car",
active: false
},
{
licence: "truck",
active: false
},
]
}
]

最佳答案

试试这个:

function comparator(){
return function(a, b){
return weightage(b)- weightage(a);
}
};

function weightage(obj){
var maxWeight = -1;
for (var i in obj.properties){
if(obj.properties[i].licence == 'truck' && obj.properties[i].active) {
maxWeight = 1;
return maxWeight;
} else if (obj.properties[i].licence == 'car' && obj.properties[i].active) {
maxWeight = 0;
}
}
return maxWeight;
};

假设您的数组名为: arr 调用 arr.sort(comparator()) 。希望这能解决您的疑问..:)

关于javascript - 对对象数组中的嵌套数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37433781/

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