Problem
I am trying to remove all of the odd numbers from an array. For example, if I pass an array like so...
var arr = [1,2,3,6,22,98,45,23,22,12]
...the function removes all of the odd numbers except for 23. Why doesn't it remove 23 as well? If different numbers are used or if the order of the numbers is changed, it is always the last odd number that is not removed. I don't understand why though, since the for loop should continue until it gets to the end of the array (i < passedArray.length).
I am sure it is something simple, but I can't figure it out! Any help would be much appreciated ;)
Code
// PROBLEM: Loop through arr removing all values that aren't even.
// The original array
var arr = [1, 2, 3, 6, 22, 98, 45, 23, 22, 12];
// Function to remove all odd numbers from the array that is passed to it.
// Returns the new array.
var getEvenNumbers = function(passedArray) {
for (var i = 0; i < passedArray.length; i++) {
// If the remainder of the current number in the array is equal to one, the number is odd so remove it from the array.
if ((passedArray[i] % 2) === 1) {
arr.splice(i, 1);
}
}
// Return the array with only even numbers left.
return passedArray;
};
// Call the function and store the results.
var evenNumbers = getEvenNumbers(arr);
// Alert the new array that only has even numbers.
alert(evenNumbers);