Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When looping through values of a JS array, and I remove value, do I need to use while instead of for?

var myArray = [1,2,3,4,5,6,7,8,9];

function isOdd(value){
    return value % 2;
}

for(var i = 0; i < myArray.length; i++){
    if(isOdd(myArray[i])){
        myArray.splice(i,1);
        i--;
    }
}

The code above takes an array of arbitrary length and checks each value. If the value of the bit of the array meets an arbitrary condition (in this case if it is odd), then it is removed from the array.

Array.prototype.splice() is used to remove the value from the array, and then i is decremented to account for the rest of the values in the array "moving down" to fill in the gap that the removed value left (so the loop doesn't skip over a value).

However, the for loop ends when i equals the length of the array, which gets shorter as values are removed.

Does the value of myArray.length decrease dynamically as the loop proceeds, or does it save the value at the start of the loop and not update as values are removed? If the latter, what can I do to fix my loop?

Thank you!

like image 243
snazzybouche Avatar asked Jun 16 '16 08:06

snazzybouche


1 Answers

myArray.length is changing with the operation on the array. But looping and splicing leads to unwanted results, if not proper padded.

To prevent unnecessary corrections, use a while loop from the end, to keep the rest of the array for processing.

function isOdd(value) {
    return value % 2;
}

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9],
    i = myArray.length;

while (i--) {
    if (isOdd(myArray[i])) {
        myArray.splice(i, 1);
    }
}
console.log(myArray);
like image 149
Nina Scholz Avatar answered Oct 15 '22 05:10

Nina Scholz