我有下面提到的2个阵列。使用此我需要根据dimentionFilterKeyOrder
中需要与dimentionFilterKeys
值进行比较的值创建一个新数组。此外,dimentionFilterKeys
中不匹配的项目需要在新数组的最后一个列表中列出。
注意:新数组Order应与dimentionFilterKeyOrder
类似。
dimentionFilterKeyOrder= ["21","22","23","14","10312","81","10315","10314"];
dimentionFilterKeys = [
{"filterKey": "81"},
{"filterKey": "82"},
{"filterKey": "10312"},
{"filterKey": "10313"},
{"filterKey": "10315"},
{"filterKey": "10314"},
{"filterKey": "20"},
{"filterKey": "21"},
{"filterKey": "22"},
{"filterKey": "23"},
{"filterKey": "24"},
{"filterKey": "14"}
]
OutPut寻找类似于下面的内容。
newArryaOutPut = [
{"filterKey": "21"},
{"filterKey": "22"},
{"filterKey": "23"},
{"filterKey": "14"},
{"filterKey": "10312"},
{"filterKey": "81"},
{"filterKey": "10315"},
{"filterKey": "10314"},
{"filterKey": "82"},
{"filterKey": "10313"},
{"filterKey": "20"},
{"filterKey": "24"}
]
答案 0 :(得分:0)
您可以使用自定义排序方法。使用filterKey
索引,您可以对对象数组进行排序。
注意:不会对dimentionFilterKeyOrder
中未移动到最后的值进行排序。 Array#sort()
执行就地排序,如果您希望取消修改原始数组,可以使用array#slice()
然后对其进行排序。
const dimentionFilterKeyOrder= ["21","22","23","14","10312","81","10315","10314"],
dimentionFilterKeys = [{"filterKey":"81"},{"filterKey":"82"},{"filterKey":"10312"},{"filterKey":"10313"},{"filterKey":"10315"},{"filterKey":"10314"},{"filterKey":"20"},{"filterKey":"21"},{"filterKey":"22"},{"filterKey":"23"},{"filterKey":"24"},{"filterKey":"14"}];
dimentionFilterKeys.sort((a,b) => {
let indexA = dimentionFilterKeyOrder.indexOf(a.filterKey),
indexB = dimentionFilterKeyOrder.indexOf(b.filterKey);
indexA = indexA == -1 ? Infinity : indexA + 1;
indexB = indexB == -1 ? Infinity : indexB + 1;
return indexA - indexB;
});
console.log(dimentionFilterKeys);

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

答案 1 :(得分:0)
这应该有效,顺序数组中不存在的键的顺序无法预测。
var compareFunc = function(a, b) {
let indexA = dimentionFilterKeyOrder.indexOf(a['filterKey']);
let indexB = dimentionFilterKeyOrder.indexOf(b['filterKey']);
if(indexA==-1)
return 1;
if(indexB==-1)
return -1;
return indexA-indexB;
}
var sorted = dimentionFilterKeys.sort(compareFunc)
答案 2 :(得分:0)
您可以使用sorting with map并将已知位置的索引和Infinity
用于排序,并保留数组的原始顺序。
var order = ["21","22","23","14","10312","81","10315","10314"],
array = [{ filterKey: "81" }, { filterKey: "82" }, { filterKey: "10312" }, { filterKey: "10313" }, { filterKey: "10315" }, { filterKey: "10314" }, { filterKey: "20" }, { filterKey: "21" }, { filterKey: "22" }, { filterKey: "23" }, { filterKey: "24" }, { filterKey: "14" }],
result = array.map(function (o, i) {
return { index: i, order: (order.indexOf(o.filterKey) + 1) || Infinity };
})
.sort(function (a, b) {
return a.order - b.order || a.index - b.index;
})
.map(function (o) {
return array[o.index];
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }