从数组中删除所有某些重复项[重复]
Posted
技术标签:
【中文标题】从数组中删除所有某些重复项[重复]【英文标题】:Removing all certain duplicates from an array [duplicate] 【发布时间】:2019-11-04 03:10:19 【问题描述】:我有两个不同的数组,我想删除第二个数组中存在的第一个数组元素的所有副本。我尝试了一些 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]
【问题讨论】:
***.com/questions/9229645/… 我想删除每个 【参考方案1】:给你
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)
设置查找:
let difference = (a, b) => (s => a.filter(x => !s.has(x)))(new Set(b))
【讨论】:
【参考方案2】:将filter
与includes
一起使用:
let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];
function func(container, removing)
let result = container.filter(e => !removing.includes(e));
return result;
console.log(func(container, removing));
ES5 语法:
var container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
var removing = [2, 3];
function func(container, removing)
var result = container.filter(function(e)
return removing.indexOf(e) == -1;
);
return result;
console.log(func(container, removing));
【讨论】:
【参考方案3】:这样就可以了:
function func(container, removing)
let result = container.filter(x => !removing.includes(x));
return result;
【讨论】:
【参考方案4】:试试这个:
let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];
const func = (container, removing) => container.filter(res=>!removing.includes(res));
console.log(func(container,removing));
【讨论】:
【参考方案5】:你可以这样做,
function func(container, removing)
let result = container.filter(data =>
if(removing.indexOf(data) < 0) return true;)
return result; // result = [1, 4, 5]
【讨论】:
以上是关于从数组中删除所有某些重复项[重复]的主要内容,如果未能解决你的问题,请参考以下文章
NodeJS - 从数组中减去数组,而不是删除所有重复项[重复]
JavaScript 数组删除重复的单词或字符(如果只输入字符。不要从 1 个单词中删除所有重复项