2 回答

TA貢獻1773條經驗 獲得超3個贊
你可以使用 array.sort
const arr1 = ['one', 'two', 'three', 'four', 'five', 'six'];
const arr2 = ['five', 'six', 'four', 'three', 'one', 'two'];
/**
Takes in a compare function as parameter where ordering is decided
based on a more less or equal to 0 return value.
More than 0 says next should have a lower index than prev
Less Than 0 puts next at a higher index and 0 keeps them at the same index
*/
arr2.sort((prev, next) => {
return arr1.indexOf(prev) - arr1.indexOf(next);
})

TA貢獻1887條經驗 獲得超5個贊
您可以獲取一個保留項目順序值的對象,并使用值的增量對第二個數組進行排序。
請查看Array#sort
并使用數字進行排序。
也許你會問,為什么不使用零作為值呢?這種方法允許通過使用這種模式來使用默認值:
array2.sort((a, b) => (order[a] || defValue) - (order[b] || defValue));
defValue
可
-Number.MAX_VALUE
一個負大數,它將所有項目無序排序到數組頂部,Number.MAX_VALUE
一個正大數,它將所有項目無序排序到數組底部,或任何其他用于在所需訂單之間進行排序的數字。
const
array1 = ['one', 'two', 'three', 'four', 'five', 'six'],
array2 = ['five', 'six', 'four', 'three', 'one', 'two'],
order = Object.fromEntries(array1.map((value, index) => [value, index + 1]));
array2.sort((a, b) => order[a] - order[b]);
console.log(...array2);
添加回答
舉報