Material Box

Material Box

WEB Design & Material Images

Godot - Sorting an Array in Ascending or Descending Order

Godot

This code example shows how to sort an array in ascending or descending order in GDScript.


Use `sort_custom()` to sort the values of an array in ascending or descending order.

var array = [15, 20, 0, 5, 10]

# Sort the array in ascending order
array.sort_custom(func(a, b): return a < b)
print(array)
# [0, 5, 10, 15, 20]

# Sort the array in descending order
array.sort_custom(func(a, b): return a > b)
print(array)
# [20, 15, 10, 5, 0]

When creating an array value sorting function as a function.

# Sort the array in ascending order
func sort_ascending(a, b):
	if a < b:
		return true
	return false

# Sort the array in descending order
func sort_descending(a, b):
	if a > b:
		return true
	return false

Godot

TitleGodot - Sorting an Array in Ascending or Descending Order

CategoryGodot

Created

Update

AuthorYousuke.U