比较两个数组并获取与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' ]
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短