for loop only works on half of the graphics??

271
3
Jump to solution
02-03-2021 03:45 PM
NickSwartz
New Contributor II

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 Honored 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
JeffK
by
Regular Contributor

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

0 Kudos
KenBuja
MVP Honored 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
NickSwartz
New Contributor II

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