如何匹配具有相同项目的 2 个不同数组的顺序?

How do I match ordering of 2 different arrays, that have the same items?

我有 2 个 javascript 数组:

const arr1 = ['one', 'two', 'three', 'four', 'five', 'six'];
const arr2 = ['five', 'six', 'four', 'three', 'one', 'two'];

PS- 我无法 change/control 订购 'arr1'

我的问题是如何使 'arr2' 的项目顺序与 'arr1' 的项目顺序相匹配。

我一直在想它可能看起来像:

//1. Some kind of function to get index of all items
const items = (item) => item === item; 
const arr3 = arr1.findIndex(items);

//2. Then think I need to get the values of arr2 using ([Array.values()][1])**
const arr2vals = arr2.values();

//3. Then some kind of calculation that matches the values, this is where I really struggle more, but weak at best lol!
arr3.filter(value => arr2vals.includes(value))

** 参考:MDN

您可以采用一个对象来保存项目的顺序值,并使用值的增量对第二个数组进行排序。

请查看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);

您可以使用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);
})

MDN docs