gpt4 book ai didi

javascript - 根据键的存在和值对对象数组进行排序

转载 作者:行者123 更新时间:2023-11-29 17:54:38 24 4
gpt4 key购买 nike

我有一个对象数组。例如-

[{
aKey:2,
bKey:2,
cKey:3
}, {
bKey:2,
cKey:6
}, {
aKey:1,
bKey:6,
cKey:5
}, {
bKey:1,
cKey:4
}, {
bKey:6,
cKey:7
}]

所以我需要做的是-

  1. 首先根据 aKey(asc 顺序)对数组进行排序,具有此键的对象将位于结果数组的开头。
  2. 然后我需要根据 bKey 的值对数组进行排序。例如,所有 bKey = 2 的记录都位于开头。
  3. 其余记录将根据 cKey 的值按 asc 顺序排序。

所以输出将是-

[{
aKey:1,
bKey:6,
cKey:5
}, {
aKey:2,
bKey:2,
cKey:3
}, {
bKey:2,
cKey:6
}, {
bKey:1,
cKey:4
}, {
bKey:6,
cKey:7
}]

最佳答案

优先排序从aKeybKey然后到cKey,你可以使用这个:

var array=[{aKey:2,bKey:2,cKey:3},{bKey:2,cKey:6},{aKey:1,bKey:6,cKey:5},{bKey:1,cKey:4},{bKey:6,cKey:7}]

var result = array.sort(function(hash) {
return function(a, b) {
return ((a.aKey || Infinity) - (b.aKey || Infinity))
|| ((a.bKey || Infinity) - (b.bKey || Infinity))
|| ((a.cKey || Infinity) - (b.cKey || Infinity))
}
}(Object.create(null)));

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

But you want bKey:2 to come before bKey:1 as for the last element that has aKey, the value of bKey is 2.

要针对此异常进行调整,在完成 aKey 后不知道要跟随哪个元素(并扩展到 bKey 的情况也完成了),你可以这样做 - 散列这些异常键并相应地排序 - 请参见下面的演示:

var array=[{aKey:2,bKey:2,cKey:3},{aKey:1,bKey:6,cKey:5},{bKey:1,cKey:4},{bKey:6,cKey:7},{bKey:2,cKey:7},{bKey:2,cKey:6},{cKey:4},{cKey:7}]

var result = array.sort(function(hash) {
return function(a, b) {
// find the anomaly keys
a.aKey && !b.aKey && (hash.bkey = a.bKey);
a.bKey && !b.bKey && (hash.ckey = a.cKey);
// sort criteria
return ((a.aKey || Infinity) - (b.aKey || Infinity))
|| (((a.bKey != hash.bkey) - (b.bKey != hash.bkey)) || ((a.bKey || Infinity) - (b.bKey || Infinity)))
|| (((a.cKey != hash.ckey) - (b.cKey != hash.ckey)) || ((a.cKey || Infinity) - (b.cKey || Infinity)))
}
}(Object.create(null)));

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

关于javascript - 根据键的存在和值对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40427593/

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