微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我有2个javascript数组:

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

PS-我无法更改/控制“ arr1”的顺序

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

我是JS菜鸟,所以请和我一起裸露(至少我正在大声笑),但是我一直在想它可能看起来像这样:

//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','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','six'];
const arr2 = ['five','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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。