比較兩個陣列並獲得不匹配的值 JavaScript


我們有兩個包含一些常見值的字面量陣列,我們的工作是編寫一個函式,該函式返回一個包含這兩個陣列中所有不常見的元素的陣列。

例如 −

// if the two arrays are:
const first = ['cat', 'dog', 'mouse'];
const second = ['zebra', 'tiger', 'dog', 'mouse'];
// then the output should be:
const output = ['cat', 'zebra', 'tiger']
// because these three are the only elements that are not common to both
arrays

讓我們編寫此程式碼 −

我們將展開這兩個陣列並過濾結果陣列以獲取一個不包含任何常見元素的陣列,如下所示 −

例項

const first = ['cat', 'dog', 'mouse'];
const second = ['zebra', 'tiger', 'dog', 'mouse'];
const removeCommon = (first, second) => {
   const spreaded = [...first, ...second];
   return spreaded.filter(el => {
      return !(first.includes(el) && second.includes(el));
   })
};
console.log(removeCommon(first, second));

輸出

控制檯中的輸出將為 −

[ 'cat', 'zebra', 'tiger' ]

更新於: 2020-08-28

4K+ 瀏覽量

啟動您的 職業

完成這門課程獲取認證

開始
廣告
© . All rights reserved.