Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
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/

share|improve this question
Wait... f is not even an index (number)! – Derek 朕會功夫 Jun 15 '12 at 21:28
fruit = fruit.filter(function(f) { return f !== "pear"; }); – squint Jun 15 '12 at 21:42

6 Answers

up vote 5 down vote accepted
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"]
share|improve this answer
Thanks! Do I have to use a loop like yours? Is it also possible using the foreach variant? – Nick Jun 15 '12 at 21:28
Try this [].forEach(). – Derek 朕會功夫 Jun 15 '12 at 21:28
3  
@Nick No it's not possible. You should never use for..in with arrays anyway. – Esailija Jun 15 '12 at 21:28
for (var i = fruit.length - 1; i > -1; i--) {
    if (fruit[i] == "pear")
        fruit.splice(i, 1);
}
share|improve this answer
2  
So where is the fruit[i] == "pear" part? – Derek 朕會功夫 Jun 15 '12 at 21:31
oeps, what a mistaka to maka, ;-) – Tom Jun 15 '12 at 21:32

If there are plenty of 'wrong' elements in the original array, I suggest at least considering not using in-place array, instead collecting all the 'right' elements into a new array:

var rightFruits = [];
for (var i = 0, len = fruit.length; i < len; ++i) {
  if (fruit[i] !== 'pear') {
    rightFruits.push(fruit[i]);
  }
}
share|improve this answer
Thanks, we used to do this approach with C#. Is it more costly to do so, instead of using a splice() ? – Nick Jun 15 '12 at 21:34
One extra variable – Derek 朕會功夫 Jun 15 '12 at 21:35
@Derek Quick question: how arrays are implemented in JavaScript? – raina77ow Jun 15 '12 at 21:36
1  
@Nick: Don't worry about performance unless it's a large collection. I'd guess that .push() may be faster when there are lots of removals, since .splice() needs to reindex the array from the current point forward every time an item is removed. Only testing will tell though. – squint Jun 15 '12 at 21:38
1  
@amnotiam Yep, you're right; it all depends on the proportion of 'bad/good' elements, but splice is usually a costly operation - especially if it's repeated, and if the array it's used on is large. – raina77ow Jun 15 '12 at 21:40
show 2 more comments
var i;
for (i = 0; i < fruits.length; i += 1) {
   if (fruits[i] == "pear") {
      fruits.splice(i, 1);
      i -= 1;
   }
}

6.4. Enumeration

Since JavaScript's arrays are really objects, the for in statement can be used to iterate over all of the properties of an array. Unfortunately, for in makes no guarantee about the order of the properties, and most array applications expect the elements to be produced in numerical order. Also, there is still the problem with unexpected properties being dredged up from the prototype chain.

Fortunately, the conventional for statement avoids these problems. JavaScript's for statement is similar to that in most C-like languages. It is controlled by three clauses: the first initializes the loop, the second is the while condition, and the third does the increment:

var i;
for (i = 0; i < myArray.length; i += 1) {
   document.writeln(myArray[i]);
}
share|improve this answer

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 );
share|improve this answer
Indeed! Too bad it can't be done with the for...in but I guess I'm just lazy. :P – Nick Jun 15 '12 at 21:38
for(var f in fruit) {
    if ( fruit[f] == "pear" ) {
        fruit.splice(f-1, 1);
    }
}

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

enjoy

share|improve this answer
f is not a number. – Derek 朕會功夫 Jun 15 '12 at 21:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.