Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a shrinking array

Suppose I have an array like this:

myArray = ["a","b","c","d","e"]

And I want to loop through it to find specific values and remove them.

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

the problem being, splice removes the item from the array, and all the items in front of the removed one, shift down an index number, so myArray.length was instantiated as 5 but after the splice myArray has a length of only 4 and the for loop fails since myArray[4] throws typeof match error in the framework.

I'm using a framework that works this way, that's why I'm utilizing such an item removal technique, my question is how to go about doing this the right way? The framework uses the splice method, I'm using the for loop, so I assume there's a correct way to go about this?

like image 980
RenaissanceProgrammer Avatar asked Feb 09 '23 17:02

RenaissanceProgrammer


1 Answers

Reverse the loop:

for(var i=myArray.length-1;i>=0;i--){
    if(myArray[i] == "b")
        myArray.splice(i,1)
}
like image 107
ergonaut Avatar answered Feb 11 '23 14:02

ergonaut