Deleting while Searching through an array, is it possible?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By dfoxworks
:warning: Old Version Published before Godot 3 was released.

Hi,

I know there’s probably an easier way to do this but I want to search through and array with dictionary entries, and if en entry is found that corresponds to the search, it will delete it. For example:

var enemies = []
enemies.append({enemy_name = "blob", enemy_position = Vector2(0, 0), enemy_health = 5})
enemies.append({enemy_name = "jelly", enemy_position = Vector2(2, 0), enemy_health = 3})
enemies.append({enemy_name = "spike", enemy_position = Vector2(5, 0), enemy_health = 4})
enemies.append({enemy_name = "claw", enemy_position = Vector2(5, 0), enemy_health = 5})	

print("Enemies: ", enemies)
var health_to_delete = 5

for i in range(enemies.size()):
	if (health_to_delete == enemies[i].enemy_health):
		enemies.erase(enemies[i])
for i in range(enemies.size()):
	print(enemies[i].name)

The results should be: “jelly, spike”
Hope this makse sense. Also this doesn’t work.
Thanks!

:bust_in_silhouette: Reply From: mollusca

To avoid issues with invalid indices you’ll have to go through the array in reverse order:

for i in range(enemies.size() - 1, -1, -1):
    if (health_to_delete == enemies[i].enemy_health):
        enemies.remove(i)