Removing an object from an array

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

Hello, I’m stuck on something apparently very simple :

I have an array with only objects in it and I’d like to remove one of those objects by naming it

var array = [obj1, obj2, obj3, obj4]
array.remove(obj3)  # > not working

remove() only works with integrals, not objects. So I have this error popping :

Invalid type in function 'remove' in base 'Array'. Cannot convert argument 1 from Object to int.

I could just write array.remove(3) but if I had removed obj2 before, for instance, then array.remove(3) would remove obj4 instead of obj3…

Is there another function I could use in this case ? :confused:
Thx !

:bust_in_silhouette: Reply From: quijipixel

What you could do is search the element you want to delete first, and once you have that’s element index, you can remove it.

var i = array.find(obj3)
array.remove(i)

What does this do to the index of the other elements?

Aaron Franke | 2019-01-16 12:31

to Aaron Franke

same as my comment up there, the index are changing

ruruarchy | 2019-06-28 13:15

:bust_in_silhouette: Reply From: volzhs

There is erase function for it.

array.erase(obj3)

What does this do to the index of the other elements?

Aaron Franke | 2019-01-16 12:31

the index is changing

pseudo code :
array = [a,b,c,d,e]
print d index , the result is: 3

erase c in array

print d index , the result is: 2

i have been test it just now

ruruarchy | 2019-06-28 13:05

I just found that this only removes the first instance of the item from the array if the item has been added multiple times.

Teyken | 2021-08-01 20:38

:bust_in_silhouette: Reply From: nonomiyo

oh, so an object is considered as a value ?

I was looking at this :

and thought only the “sort_custom” function could deal with objects…

thanks for your clarifications guys !