0

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.

1
  • Can you just check if currentMarkers[m] exists before trying to call the remove method? If optional chaining is available, this could be as easy as currentMarkers[m]?.remove(). If not, you could do something like currentMarkers[m] && currentMarkers[m].remove() Commented Jul 4, 2021 at 23:41

2 Answers 2

1

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hey thanks for answering !! But for some reason it still shows that error. The one @thomson gave seems to work.
0

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.
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.