在具有多个出现次数的数组中循环删除一个元素

23

我想用一个函数从一个包含多个重复元素的数组中删除一个元素。

var array=["hello","hello","world",1,"world"];

function removeItem(item){
    for(i in array){
        if(array[i]==item) array.splice(i,1);
    }
}
removeItem("world");
//Return hello,hello,1
removeItem("hello");
//Return hello,world,1,world

这个循环在连续重复两次时不会移除其中一个元素,只会移除其中一个。

为什么?


这个能用吗?变量i将不等于数组的索引,而只是变量数组的成员。 - Captain John
11个回答

0

我认为这段代码更简单易懂,不需要手动传递每个要删除的元素

ES6语法让我们的生活变得更加简单,试一试吧

const removeOccurences = (array)=>{
const newArray= array.filter((e, i ,ar) => !(array.filter((e, i ,ar)=> i !== ar.indexOf(e)).includes(e)))
console.log(newArray) // output [1]
}
removeOccurences(["hello","hello","world",1,"world"])


donArray未定义。无论如何,这不是问题,OP只想删除特定元素,而不是删除所有重复项。为此,您可以使用Set:Array.from(new Set(arrayThatContainsDuplicates)); - jona303

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接