[英]Sorting an array of object based on key existence and value
我有一個對象數組。 對於例如
[{
aKey:2,
bKey:2,
cKey:3
}, {
bKey:2,
cKey:6
}, {
aKey:1,
bKey:6,
cKey:5
}, {
bKey:1,
cKey:4
}, {
bKey:6,
cKey:7
}]
所以我需要做的是-
因此輸出將是-
[{
aKey:1,
bKey:6,
cKey:5
}, {
aKey:2,
bKey:2,
cKey:3
}, {
bKey:2,
cKey:6
}, {
bKey:1,
cKey:4
}, {
bKey:6,
cKey:7
}]
您可以像這樣使用sort()
var data = [{ aKey:2, bKey:2, cKey:3 }, { bKey:2, cKey:6 }, { aKey:1, bKey:6, cKey:5 }, { cKey:41 }, { cKey:7 }, { bKey:1, cKey:4 }, { bKey:6, cKey:7 }] data.sort(function(a, b) { return ((b.aKey != undefined) - (a.aKey != undefined) || a.aKey - b.aKey) || ((b.bKey != undefined) - (a.bKey != undefined) || ((a.bKey != 2) - (b.bKey != 2)) || a.bKey - b.bKey) || ((b.cKey != undefined) - (a.cKey != undefined) || a.cKey - b.cKey) }) console.log(data)
為了優先排序從aKey
到bKey
,然后到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;}
但是你要
bKey:2
來之前bKey:1
作為具有最后一個元素aKey
,價值bKey
是2
。
要對此異常進行調整,而又不知道aKey
完成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;}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.