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?
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?
Share Improve this question asked Aug 15, 2014 at 0:06 user3566643user3566643 5351 gold badge4 silver badges8 bronze badges 2 |5 Answers
Reset to default 7Yes, 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
}
}
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).
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; } );
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--;
arr.filter(function(item){return item % 2;}));
for-loop through array
problem. – Zhouster Commented Aug 15, 2014 at 0:10