The reduce Method
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 62 of 78.
reduce() combines all the elements of an array into one value: a sum, a product, the largest element, a sentence.
var numbers = [1, 2, 3, 4]
var total = numbers.reduce(func(acc, n): return acc + n, 0)
print(total)10It takes two arguments: a function and a start value, here 0. The function receives the result so far, called the accumulator (acc), and the next element. What it returns becomes the new accumulator:
accstarts at00 + 1is1,1 + 2is3,3 + 3is6,6 + 4is10- after the last element,
reduce()returns the accumulator:10
For a product, start at 1: numbers.reduce(func(acc, n): return acc * n, 1) is 24.
Without a start value, the first element is the start and the function runs from the second element on. That suits the largest element:
var biggest = [4, 9, 2].reduce(func(a, b): return a if a > b else b)
print(biggest) # 9On an empty array without a start value, reduce() returns null, so give a start value when the array can be empty.
The accumulator can have any type. With a start value of "", this builds a String from the first letters:
var words = ["game", "over"]
print(words.reduce(func(acc, w): return acc + w[0], "")) # goChallenge
EasyThe program reads one line of whole numbers separated by commas and stores them in the array numbers. This part is already written.
Using reduce() for each of them, print three lines:
- the sum of the numbers
- their product
- the largest number (write the comparison in the lambda; do not call
max())
There is always at least one number. For the input 3,7,2,8,4, the output is:
24
1344
8Try it yourself
extends Node
func _ready():
var numbers := []
for part in OS.read_string_from_stdin().split(","):
numbers.append(int(part))
# Print the sum, the product and the largest number, each with reduce()
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