Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete specific array elements from within a foreach loop in javascript

var fruit = ["apple","pear","pear","pear","banana"];

How do I remove all "pear" fruit from this array?
I tried the following, but still one pear remains:

for(var f in fruit) {
    if ( fruit[f] == "pear" ) {
        fruit.splice(f, 1);
    }
}

for(var f in fruit) {
    document.write(fruit[f]+"<br>");        
}

Outputs:

apple 
pear 
banana

​What am I doing wrong? Live demo: http://jsfiddle.net/SbxHc/

like image 536
Nick Avatar asked Jun 15 '12 21:06

Nick


People also ask

How do I remove a specific part of an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

Can we remove any element by using it for each loop?

Can we remove an element by using forEach loop? The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove .

How do you remove the elements of an array from the array in JavaScript?

Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.

How do you remove an element from an array at a specific index JavaScript?

You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove.


3 Answers

var fruit = ["apple", "pear", "pear", "pear", "banana"],
    i;

for (i = 0; i < fruit.length; ++i) {
    if (fruit[i] === "pear") {
        fruit.splice(i--, 1);
    }
}

console.log(fruit);
//["apple", "banana"]
like image 53
Esailija Avatar answered Sep 20 '22 21:09

Esailija


for (var i = fruit.length - 1; i > -1; i--) {
    if (fruit[i] == "pear")
        fruit.splice(i, 1);
}
like image 42
Tom Avatar answered Sep 20 '22 21:09

Tom


When you remove items from an array as you iterate over it, you would generally iterate backwards so that the current index doesn't skip over items as you remove them:

var fruit = ["apple","pear","pear","pear","banana"];
var i;

for (i = fruit .length - 1; i >= 0; i--) {
    if (fruit [i] === "pear") {
        fruit .splice(i, 1);
    }        
}

console.log(fruit );
like image 20
Tuan Avatar answered Sep 19 '22 21:09

Tuan