簡體   English   中英

根據鍵的存在和值對對象數組進行排序

[英]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
}]

所以我需要做的是-

  1. 首先根據aKey(升序)對數組進行排序,擁有此鍵的對象將位於結果數組的開頭。
  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
}]

您可以像這樣使用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) 

為了優先排序從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;} 

但是你要bKey:2來之前bKey:1作為具有最后一個元素aKey ,價值bKey2

要對此異常進行調整,而又不知道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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM