2 回答

TA貢獻1826條經(jīng)驗 獲得超6個贊
要排序,您必須首先檢查長度。如果兩者相等,我們必須檢查a/b中第一個元素的索引位置key。如果它們相同,則繼續(xù)移動到兩個數(shù)組中的下一個元素。
這個答案利用了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條經(jīng)驗 獲得超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)
添加回答
舉報