首页 > 解决方案 > 从数组中删除所有某些重复项

问题描述

我有两个不同的数组,我想删除第二个数组中存在的第一个数组元素的所有副本。我尝试了一些 splice 和 indexOf 方法,但无法实现。检查了其他一些帖子,但找不到我正在寻找的内容。下面是一个示例代码。谢谢你们。

let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];


function func(container, removing){
  let result = //i want to write a function there which will remove all duplicates of "removing" from "container".
  return result; // result = [1, 4, 5]
}

标签: javascriptarrays

解决方案


干得好

let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];


let difference = (a, b) => a.filter(x => !b.includes(x));

console.log(difference(container, removing))

如果出于某种原因,您担心这样做的效率,您可以将线性includes检查替换为O(1)Set 查找:

let difference = (a, b) => (s => a.filter(x => !s.has(x)))(new Set(b))

推荐阅读