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?
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).
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
}
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With