比较两个数组并获得不匹配的值 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