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

Sorting an array of object based on key existence and value

本文关键字:数组 对象 排序 存在      更新时间:2023-09-26

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

[{
    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. 首先根据key (asc顺序)对数组进行排序,具有该key的对象将位于结果数组的开头。
  2. 然后我需要根据bKey的值对数组进行排序。例如,所有具有bKey = 2的记录将位于开头。
  3. 其余记录将根据key的值按顺序排序。

那么输出将是-

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

要优先从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:2bKey:1之前作为最后一个元素如果有aKey,则bKey的值为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;}

您可以像这样使用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)