javascript - 从数组中删除所有某些重复项
问题描述
我有两个不同的数组,我想删除第二个数组中存在的第一个数组元素的所有副本。我尝试了一些 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]
}
解决方案
干得好
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))
推荐阅读
- onclick - alpine.js,如何使元素在 self @click 上消失?
- python - How to load cudf in colab?
- javascript - 如何在 vue.js 中迭代数据
- sharepoint - 有没有办法让 SPFx 自定义 webpart 占据整个空间?
- javascript - 如何检查 MongoDB 字段的值是否在字符串中?
- tensorflow - 用于部署的 CNN 模型:如何优化
- c# - 有没有办法使用不同名称的控制器和视图但仍然能够显示错误属性消息?
- javascript - 如何交叉过滤 2 dc.js SeriesChart?
- scala - Akka Stream - 带分区的并行处理
- hapi-fhir - StructureDefinition 发布请求返回 404 错误