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 == 0var 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
EasyWrite 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student11Higher-Order Functions
The map MethodThe filter MethodThe reduce Methodany and allRecap - Email ValidatorRecap - Number Processor3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler