Menu
CoddyTech

Recap - Sum Nested Array

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 59 of 78.

challenge icon

Challenge

Easy

Write a recursive function named sum_nested that takes an array nested_array. Its elements are whole numbers or other arrays, which can hold more numbers and arrays, at any depth.

The function returns the sum of every number in it, at every level.

To tell the two kinds of elements apart, use is Array: element is Array is true when element is an array.

For example, sum_nested([1, [2, 3], [4, [5, 6]], 7]) returns 28. An empty array sums to 0.

The tests call sum_nested() themselves. Do not call it, and do not print anything.

Try it yourself

func sum_nested(nested_array: Array):
	var total := 0
	for element in nested_array:
		if element is Array:
			# Add the sum of this inner array to total
			pass
		else:
			# Add the number to total
			pass
	return total

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler