Menu
CoddyTech

The filter Method

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

filter() calls a function on every element and keeps only the elements for which it returns true. It returns them in a new array, in their original order:

func is_even(n):
	return n % 2 == 0
var numbers = [1, 2, 3, 4, 5, 6]
print(numbers.filter(is_even))
[2, 4, 6]

is_even(1) returns false, so 1 is dropped. is_even(2) returns true, so 2 is kept, and so on.

With a lambda, the condition sits right in the call:

var words = ["apple", "banana", "cherry", "date"]
print(words.filter(func(w): return w.length() > 5))
["banana", "cherry"]

The result can be shorter than the original, or even empty, and the original array does not change. On a typed array such as Array[String], filter() returns an array of the same type.

filter() and map() both return arrays, so you can chain them. This keeps the even numbers and then squares them:

print(numbers.filter(is_even).map(func(n): return n * n))
[4, 16, 36]
challenge icon

Challenge

Easy

Write a function named get_long_strings that takes an array of strings, strings, and returns a new array with only the strings that are longer than 5 characters, in their original order.

Use filter() with a lambda, and no loop. For example, get_long_strings(["apple", "banana", "cherry", "fig"]) returns ["banana", "cherry"].

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

Try it yourself

func get_long_strings(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