首页 文章资讯内容详情

比较两个数组并获取与JavaScript不匹配的那些值

2026-06-05 1 花语

我们有两个包含一些公共值的文字数组,我们的工作是编写一个函数,该函数返回一个数组,其中包含两个数组中所有不常见的元素。

例如-

// 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 ]