Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

javascript - Loop to remove an element in array with multiple occurrences

I want to remove an element in an array with multiple occurrences with a function.

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

This loop doesn't remove the element when it repeats twice in sequence, only removes one of them.

Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have a built in function called filter that filters an array based on a predicate (a condition).

It doesn't alter the original array but returns a new filtered one.

var array=["hello","hello","world",1,"world"];
var filtered = array.filter(function(element) {
    return element !== "hello";
}); // filtered contains no occurrences of hello

You can extract it to a function:

function without(array, what){
    return array.filter(function(element){ 
        return element !== what;
    });
}

However, the original filter seems expressive enough.

Here is a link to its documentation

Your original function has a few issues:

  • It iterates the array using a for... in loop which has no guarantee on the iteration order. Also, don't use it to iterate through arrays - prefer a normal for... loop or a .forEach
  • You're iterating an array with an off-by-one error so you're skipping on the next item since you're both removing the element and progressing the array.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...