比較兩個陣列並獲得不匹配的值 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' ]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP