Unable to remove even numbers from my array

I am trying to remove all even numbers from an array, but it just does not 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 it - [3, 45, 7, 56, 345] instead [3, 45, 7, 345]

Any ideas?

+7
javascript arrays
source share
5 answers

Yes, this is because when you connect 1 element from an array, the length of the array changes. Try it -

 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 } } 
+7
source share

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

You need to be careful when updating the array, iterating over it.

In this case, you can i-- over the array backward (start from the end, do i-- ). Depending on how splicing is implemented, it can even be a little faster (potentially fewer array elements are copied).

+6
source share

The length of your array changes when you remove elements from it.

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

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

You iterate over your array through i, which grows every time. After it gets to 88, it will merge it and still increase the array, which will skip 56, and the next one I will refer to 34.

You either do not need to increase I when splicing, or when you splicing, just I -;

+5
source share
 arr.filter(function(item){return item % 2;})); 
+4
source share

All Articles