Select to view content in your preferred language

for loop only works on half of the graphics??

856
3
Jump to solution
02-03-2021 03:45 PM
NickSwartz
Emerging Contributor

Trying to loop through all graphics in view and delete ones that have geometry = "polyline"

 const graphicsArr = view.graphics;
            console.log(graphicsArr.length)
            console.log(graphicsArr)

            if (graphicsArr.length > 0) {
                for (const graphic of graphicsArr.items) {
                    console.log(graphic)
                    if (graphic.geometry.type == "polyline") {
                        view.graphics.remove(graphic)
                    }
                }
            }
 
When I console.log my array of graphics, the length is twelve, but the loop only runs 6 times.  Very frustrating.  Anybody know what is going on?
0 Kudos
1 Solution

Accepted Solutions
KenBuja
MVP Esteemed Contributor

When you remove items from an array using a loop, you have to loop through the array in reverse, removing the last item.

 

const graphicsArr = view.graphics;
if (graphicsArr.length > 0) {
  for (let i = graphicsArr.length - 1; i >= 0; i--) {
    console.log(graphicsArr[i])
    if (graphicsArr[i].geometry.type == "polyline") {
      view.graphics.remove(graphicsArr[i])
    }
  }
}

 

View solution in original post

0 Kudos
3 Replies
by Anonymous User
Not applicable

Could it be that you are iterating over the graphicsArr, but are removing the item from the view.graphics directly?

0 Kudos
KenBuja
MVP Esteemed Contributor

When you remove items from an array using a loop, you have to loop through the array in reverse, removing the last item.

 

const graphicsArr = view.graphics;
if (graphicsArr.length > 0) {
  for (let i = graphicsArr.length - 1; i >= 0; i--) {
    console.log(graphicsArr[i])
    if (graphicsArr[i].geometry.type == "polyline") {
      view.graphics.remove(graphicsArr[i])
    }
  }
}

 

0 Kudos
NickSwartz
Emerging Contributor

Wow, thank you.  I ended up just creating graphics layers and clearing out all graphics associated with a given layer when I added a different layer (rather than doing it by geometry type).  But this solution will be super valuable in the future.  Thanks, Ken!

0 Kudos