Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  113] [ 4]  / answers: 1 / hits: 15735  / 12 Years ago, fri, june 15, 2012, 12:00:00
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/


More From » arrays

 Answers
21
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]

[#84871] Thursday, June 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
juancarlos

Total Points: 580
Total Questions: 105
Total Answers: 103

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
;