2 回答

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
你可以使用 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貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以獲取一個(gè)保留項(xiàng)目順序值的對(duì)象,并使用值的增量對(duì)第二個(gè)數(shù)組進(jìn)行排序。
請(qǐng)查看Array#sort
并使用數(shù)字進(jìn)行排序。
也許你會(huì)問,為什么不使用零作為值呢?這種方法允許通過使用這種模式來使用默認(rèn)值:
array2.sort((a, b) => (order[a] || defValue) - (order[b] || defValue));
defValue
可
-Number.MAX_VALUE
一個(gè)負(fù)大數(shù),它將所有項(xiàng)目無序排序到數(shù)組頂部,Number.MAX_VALUE
一個(gè)正大數(shù),它將所有項(xiàng)目無序排序到數(shù)組底部,或任何其他用于在所需訂單之間進(jìn)行排序的數(shù)字。
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);
添加回答
舉報(bào)