Menu
CoddyTech

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)
10

It 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:

  • acc starts at 0
  • 0 + 1 is 1, 1 + 2 is 3, 3 + 3 is 6, 6 + 4 is 10
  • 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) # 9

On 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], "")) # go
challenge icon

Challenge

Easy

The 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:

  1. the sum of the numbers
  2. their product
  3. 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
8

Try 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()
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