亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何匹配具有相同項目的 2 個不同數組的順序?

如何匹配具有相同項目的 2 個不同數組的順序?

MMMHUHU 2023-03-24 13:58:16
我有 2 個 javascript 數組:const arr1 = ['one', 'two', 'three', 'four', 'five', 'six'];const arr2 = ['five', 'six', 'four', 'three', 'one', 'two'];PS-我無法更改/控制“arr1”的順序我的問題是如何使“arr2”的項目順序與“arr1”的項目相匹配。我一直在想它可能看起來像://1. Some kind of function to get index of all itemsconst 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
查看完整描述

2 回答

?
慕容3067478

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);

})

MDN 文檔


查看完整回答
反對 回復 2023-03-24
?
慕工程0101907

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);


查看完整回答
反對 回復 2023-03-24
  • 2 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號