You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript ES6 filter方法提取两个数组的非共有元素

解决方案

你可以借助ES6的Array.prototype.filter()和Array.prototype.includes()方法实现需求,直接从newArray中筛选出existingArray不包含的元素:

const existingArray = [10,20,30,40];
const newArray = [10,20,30,40,50,60,70];
const updatedArray = newArray.filter(item => !existingArray.includes(item));

console.log(updatedArray); // 输出: [50, 60, 70]

代码说明

  • filter()会遍历newArray的每一个元素,仅保留回调函数返回true的元素,最终组成新数组
  • includes()用于判断当前元素是否存在于existingArray中,取反后就会筛选出两个数组的非共有元素

性能优化方案(适用于大数据量场景)

如果数组元素数量较多,includes()的O(n)时间复杂度会影响性能,这时可以先把existingArray转为Set(Set.has()的时间复杂度是O(1)),再结合filter()使用:

const existingArray = [10,20,30,40];
const newArray = [10,20,30,40,50,60,70];
const existingSet = new Set(existingArray);
const updatedArray = newArray.filter(item => !existingSet.has(item));

console.log(updatedArray); // 输出: [50, 60, 70]

内容的提问来源于stack exchange,提问作者sourabhk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:50:55