Menu
CoddyTech

The map Method

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

A higher-order function is a function that takes another function as an argument. Arrays have several of them, and map() is the first.

map() calls a function on every element of an array and returns a new array with the results, in the same order:

func square(n):
	return n * n
var numbers = [1, 2, 3, 4, 5]
var squares = numbers.map(square)
print(squares)
[1, 4, 9, 16, 25]

Pass the function by its name, without parentheses: map(square) hands the function over, while map(square()) would try to call it right away. map() then calls it once for each element: 1 becomes 1, 2 becomes 4, 3 becomes 9, and so on.

For a short calculation, a lambda saves you the separate function:

var squares = numbers.map(func(n): return n * n)

The new array has the same size as the original, and numbers itself does not change. The results can have another type than the elements:

var words = ["apple", "kiwi", "banana"]
print(words.map(func(w): return w.length()))
[5, 4, 6]

map() returns a plain Array, even when you call it on a typed one like Array[int]. Storing that result in an Array[int] variable stops the program with an error, so store it in an untyped variable or an Array.

split() returns a PackedStringArray, which has no map(). Turn it into an Array first: Array("1,2,3".split(",")).map(func(s): return int(s)) gives [1, 2, 3].

challenge icon

Challenge

Easy

Write a function named convert_to_uppercase that takes an array of strings, strings, and returns a new array with every string in upper case.

Use map() with a lambda, and no loop. For example, convert_to_uppercase(["hello", "world"]) returns ["HELLO", "WORLD"].

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

Try it yourself

func convert_to_uppercase(strings: Array[String]):
	# Write code here
	pass
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler