7

I am trying to delete all even numbers from the array but it just doesnt delete all of them . not sure why

 var arr = [3,45,56,7,88,56,34,345];    
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] % 2 === 0) {
        arr.splice(i,1);
      }
    }

console.log(arr); gives this - [3, 45, 7, 56, 345] instead of this [3, 45, 7, 345]

Any ideas?

2
  • The classic for-loop through array problem. Commented Aug 15, 2014 at 0:10
  • 2
    add the numbers you want to keep to a new array, when done remove old arr and use new one. Commented Aug 15, 2014 at 0:16

5 Answers 5

7

Yes, that is because when you splice out 1 element from an array the length of array is changed. Try this -

var arr = [3,45,56,7,88,56,34,345];

for (var i = 0; i < arr.length; i++) {
  if (arr[i] % 2 === 0) {
    arr.splice(i,1);
    i = i-1; // SINCE YOU DELETED ONE ELEMENT, 
             // THE NEXT ELEMENT IN THE ARRAY GETS SHIFTED TO ONE POSITION ABOVE 
             //(SAY, FROM INDEX 4 TO 3). SO, YOU WILL NEED TO CHECK FROM INDEX 3 NOT 4
  }
}
Sign up to request clarification or add additional context in comments.

Comments

6

When you delete 88, the 56 following it moves up one position, and your loop skips it (it just does i++).

You need to be careful when updating an array while iterating over it.

You could iterate the array backwards in this case (start at the end, do i--). Depending on how splice is implemented, this could even be a bit faster (potentially fewer array elements are getting copied around).

Comments

6

The length of your array changes as you delete elements from it.

I would suggest using Array.prototype.filter to achieve this (which is easily shimmed for IE <= 8):

var arr = [3,45,56,7,88,56,34,345];    
arr = arr.filter( function is_odd(el) { return el % 2; } );

1 Comment

Array.filter isn't available on older browsers, but this is the best modern approach +1
5

You are looping through your array via i which is incremented every time. After it gets to 88, it splices it out, and still increases the array, which will skip over the 56, the next i will refer to 34.

You either need to not increment i when you splice, or, when you splice, simply i--;

Comments

4
arr.filter(function(item){return item % 2;}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.