簡體   English   中英

如何獲得兩個字符串數組的區別?

[英]How to get the difference of two string arrays?

我想得到兩個字符串數組之間的確切區別。

const array1 = ['T','E','A','P','A','P','E','R'];
const array2 = ['T','A','P'];

預期輸出數組:

['E','A','P','E','R']

我試過這個方法:

const output = array1.filter(char => array2.includes(char));

但是這會刪除角色的所有實例,例如:

['E','E','R']

我是新手,你能引導我走向正確的方向嗎?

您可以對第二個數組的索引進行閉包,並遞增索引並從結果集中刪除此項。

 var array1 = ['T', 'E', 'A', 'P', 'A', 'P', 'E', 'R'], array2 = ['T', 'A', 'P'], result = array1.filter((i => v => array2[i] !== v || !++i)(0)); console.log(result); 

沒有預定義的array2順序的不同方法。

 var array1 = ['T', 'E', 'A', 'P', 'A', 'P', 'E', 'R'], array2 = ['T', 'A', 'P'], set2 = new Set(array2) result = array1.filter(v => !set2.delete(v)); console.log(result); 

我認為過濾器在這里不正確。 因為有一些元素被重復了。 使用簡單的for循環。 將結果添加到結果中時刪除元素。

 const array1 = ['T','E','A','P','A','P','E','R']; const array2 = ['T','A','P']; const copy = [...array2]; let res = []; for(let i = 0;i<array1.length;i++){ let index = copy.indexOf(array1[i]); if(index === -1){ res.push(array1[i]); } else copy.splice(index,1); } console.log(res) 

您可以根據input數組從allowed刪除元素:

 const allowed = ['T','E','A','P','A','P','E','R'];
 const input = ['T','A','P'];

 for(const char of input) {
   const pos = allowed.indexOf(char);
   if(pos === -1) {
     // char doesnt exist?
   } else {
     allowed.splice(pos, 1);
   }
 }

然后allowed將是您最終的預期結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM