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?
Reverse the loop:
for(var i=myArray.length-1;i>=0;i--){
if(myArray[i] == "b")
myArray.splice(i,1)
}
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