using .find() to find the index of an item in an array of arrays

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ShroudedFox

So I have an array lets say its organised like this

var array = [[[node], [19, 0, 0], "there"], [[node], [13, 2, 2], "here"]

im looking to find the array index that contains “here”
so i want to use .find() to return the value 1

in documentation it says

int find ( Variant what, int from=0 )
for some reason just cant get my head around how to use it to search in a layered array

like i could right a function like so

var array = [[[node], [19, 0, 0], "there"], [[node], [13, 2, 2], "here"]

func find_Index(search_for):
   var i = 0
   while i < array.size():
      if array [i][2] == search_for:
         return (i)
      i += 1
   return (-1)

but i want to learn how to use .find becasue it seems simpler :S

:bust_in_silhouette: Reply From: Tim Martin

You could change to for i in range(array.size()):

And to if array[i].find(search_for) != -1: if you don’t want to force the thing you’re searching for to be always the third element of the nested arrays.

Otherwise, your implementation looks good to me. You need your own function here as you need to make it work with your custom data structure.

:bust_in_silhouette: Reply From: Ahmed

Hi, I’m new in GDScript please correct me if I’m wrong.

The find method in the Array class there is a limitation, it can’t search an item inside an array (Nested Array).

If you do this

var array = [[["this"], [19, 0, 0], "there"], [["node"], [13, 2, 2], "here"]]
for i in range(array.size()):
     print("Item[" + String(i) + "] = " + String(array[i]))

Result would be:_

Item[0] = [[this], [19, 0, 0], there]
Item[1] = [[node], [13, 2, 2], here]]

So you have write your custom search for that particular Array.