Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  9] [ 5]  / answers: 1 / hits: 24522  / 11 Years ago, sun, december 22, 2013, 12:00:00

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?


More From » arrays

 Answers
220

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.


[#73596] Saturday, December 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
Mon, Oct 18, 21, 00:00, 3 Years ago
Thu, Oct 14, 21, 00:00, 3 Years ago
Thu, Jul 15, 21, 00:00, 3 Years ago
Sat, Oct 24, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;