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?
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With