jot
jot

Reputation: 185

How to skip the undefined values in an array while running the for loop

I have several checkboxes in my webpage table. When the user checks a checkbox (eg number 10) , a marker for number 10 and is saved to my array "currentMarkers" in the 10th position.

this.currentMarkers[j] = mymarker;  // where j is the number selected by user

Now only the 10th position in the array " currentMarkers" has a value and the rest are undefined since only one checkbox is clicked.

Now the problem I'm facing is that, when i click a main check box i need to clear all the markers in the map by removing the markers from the array. But since currentMarkers[0] has an undefined value ,it shows an error and stops and cannot go forward and remove the currentMarkers[1] , currentMarkers[2] and so on .

for(let m =0; m <12; m++){
currentMarkers[m].remove(); // stops as currentMarkers[0] undefined.
}

NOTE: If i use the clear array methods the markers will be still in the map. I can only use the .remove() method to remove the markers one by one from the map, and that's why i used the for loop

Is there any way i can look which array values actually have data and use a for loop to iterate through them?

Any help is appreciated. Thanks a lot for your time.

Upvotes: 0

Views: 1630

Answers (2)

Thomson Mixab
Thomson Mixab

Reputation: 657

To remove only array element that has value. https://love2dev.com/blog/javascript-remove-from-array/

for(let m =0; m <12; m++){
    if(currentMarkers[m] != undefined || currentMarkers[m] != null) 
    {
        currentMarkers[m].remove(); // stops as currentMarkers[0] undefined.
    }
}

Upvotes: 0

Slava Knyazev
Slava Knyazev

Reputation: 6081

The simplest method would be to check for it, and invoke continue to skip to the next iteration of the loop:

for(let m =0; m <12; m++){
   if (currentMarkers[m] == undefined) continue;
   currentMarkers[m].remove();
}

Upvotes: 1

Related Questions