Flatten Array #

If you’ve worked with multidimensional arrays before you’ve probably come across a time where you need to flatten that array, say an inventory system but you need to iterate through each item for example. The below snippet takes a multidimensional array as a parameter and returns a flattened 1D array.

Since the function works recursively, it flattens all arrays in the parameter no matter how deep. This might not be ideal for your use-case, so a second depth parameter could be added to track how deep the function gets and where it should stop.

## Flattens a multidimensional array into a 1D array
func flatten_array(array: Array) -> Array:
	var flat_array = []
	
	for item in array:
		if item is Array:
			flat_array.append_array(flatten_array(item))
		else:
			flat_array.push_back(item)
	
	return flat_array