使用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
相关产品推荐
相关产品推荐

