I want to remove an element in an array with multiple occurrences with a function.
JavaScript
x
8
1
var array=["hello","hello","world",1,"world"];
2
3
function removeItem(item){
4
for(i in array){
5
if(array[i]==item) array.splice(i,1);
6
}
7
}
8
JavaScript
1
3
1
removeItem("world");
2
//Return hello,hello,1
3
JavaScript
1
3
1
removeItem("hello");
2
//Return hello,world,1,world
3
This loop doesn’t remove the element when it repeats twice in sequence, only removes one of them.
Why?
Advertisement
Answer
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.
JavaScript
1
5
1
var array=["hello","hello","world",1,"world"];
2
var filtered = array.filter(function(element) {
3
return element !== "hello";
4
}); // filtered contains no occurrences of hello
5
You can extract it to a function:
JavaScript
1
6
1
function without(array, what){
2
return array.filter(function(element){
3
return element !== what;
4
});
5
}
6
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 normalfor...
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.