第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何匹配具有相同項(xiàng)目的 2 個(gè)不同數(shù)組的順序?

如何匹配具有相同項(xiàng)目的 2 個(gè)不同數(shù)組的順序?

MMMHUHU 2023-03-24 13:58:16
我有 2 個(gè) javascript 數(shù)組:const arr1 = ['one', 'two', 'three', 'four', 'five', 'six'];const arr2 = ['five', 'six', 'four', 'three', 'one', 'two'];PS-我無法更改/控制“arr1”的順序我的問題是如何使“arr2”的項(xiàng)目順序與“arr1”的項(xiàng)目相匹配。我一直在想它可能看起來像://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貢獻(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);

})

MDN 文檔


查看完整回答
反對(duì) 回復(fù) 2023-03-24
?
慕工程0101907

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


查看完整回答
反對(duì) 回復(fù) 2023-03-24
  • 2 回答
  • 0 關(guān)注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)