2 回答
TA贡献1826条经验 获得超6个赞
要排序,您必须首先检查长度。如果两者相等,我们必须检查a/b中第一个元素的索引位置key。如果它们相同,则继续移动到两个数组中的下一个元素。
这个答案利用了0一个虚假价值的事实。例子是:0 || -1 //=> -1和1 || -1 //=> 1
const key = ["meraki", "active directory", "sophos"];
const raw = [
["meraki"],
["active directory"],
["sophos", "active directory"],
["active directory", "sophos"],
["sophos"],
["meraki", "active directory", "sophos"],
];
raw.sort((a, b) => (
a.length - b.length || a.reduce((diff, _, i) => (
diff || key.indexOf(a[i]) - key.indexOf(b[i])
), 0)
));
console.log(raw);
console.table(raw); // check browser console
TA贡献1812条经验 获得超5个赞
考虑以下方法
const key = [
"meraki",
"active directory",
"sophos"
]
const raw = [
["sophos"],
["meraki"],
["active directory"],
["sophos", "active directory"],
["active directory", "sophos"],
["meraki", "active directory", "sophos"]
]
const compareThis = (a, b) => {
if (a.length !== b.length) {
return a.length - b.length
}
let itemFound = 0;
for (let keyIndex in key) {
for (let aIndex in a ) {
if(a[aIndex] === key[keyIndex]) {
itemFound = -1;
break;
}
if(b[aIndex] === key[keyIndex]) {
itemFound = 1;
break;
}
}
if(itemFound !== 0) { break }
}
return itemFound;
}
const sortedData = raw.sort(compareThis)
console.log(sortedData)
添加回答
举报