easiest way to loop into multidimensional array without knowing what dimension it is

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

Hello, just a simple question

I want to make a one dimensional array from an array that looks like : [ [ ] , [ ],… ]
is there another way than looping into each arrays of arrays of arrays and appending ?
a solution for array that would be either 3 or 4 or whatever dimension ?

for i in (complex_array.size()):
>for h in (complex_array[i].size()):
>>for j in (complex_array[h].size()):
>>>simple_array.append(j)

thx

:bust_in_silhouette: Reply From: SIsilicon

I’m so glad recursive functions are supported in gdscript.

func traverse_nested_array(arr): 
    for i in arr:
        if typeof(i) == TYPE_ARRAY:
            traverse_nested_array(i)
        else:
            simple_array.append(i)

Let me explain this to you. When a programming language allows recursive functions, the programmer can call the same function inside itself. This shows how I used this to my benefit.

  • First pass the array into the function.
  • Inside the function you go through each element of that passed array.
  • If the element is itself an array, then you call the same function inside this function, but with this array passed in instead.
  • If it isn’t, you do whatever you want to do to the element. In this example add it to a different array.

Here simple_array is defined globally in a script. If it was a local variable inside a different function, then you’d have to pass it into this recursive function with the following modification.

func traverse_nested_array(arr, simple_array): 
    for i in arr:
        if typeof(i) == TYPE_ARRAY:
            traverse_nested_array(i, simple_array) #pass the parameter into the same one.
        else:
            simple_array.append(i)

Thank you, best answer solution I could ever expect.

Asoth | 2018-11-17 07:11

You’re welcome. :wink:

SIsilicon | 2018-11-17 13:33