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/
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 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 .
Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.
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.
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"]
for (var i = fruit.length - 1; i > -1; i--) {
if (fruit[i] == "pear")
fruit.splice(i, 1);
}
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 );
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