Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot delete even numbers from my array

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?

like image 430
user3566643 Avatar asked Aug 15 '14 00:08

user3566643


People also ask

How do you remove odd numbers from an array?

filter method. var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var output = arr. filter(function(item) { return item % 2 === 0; }); Output will be a new array of the filtered values (Only even).


2 Answers

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
  }
}
like image 124
Cute_Ninja Avatar answered Sep 26 '22 06:09

Cute_Ninja


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).

like image 44
Thilo Avatar answered Sep 22 '22 06:09

Thilo