Min and Max values in an array

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By vonflyhighace2
:warning: Old Version Published before Godot 3 was released.

How would I be able to get the Min and Max values from an array of integers.

:bust_in_silhouette: Reply From: avencherus

Not sure if there is an apply function to arrays in Godot. That’s usually the built in way of doing it. You could write functions like these to do the work:

func min_arr(arr):
	var min_val = arr[0]
	
	for i in range(1, arr.size()):
		min_val = min(min_val, arr[i])

	return min_val

func max_arr(arr):
	var max_val = arr[0]
	
	for i in range(1, arr.size()):
		max_val = max(max_val, arr[i])

	return max_val

Or another idea, if you want to do both in the same function and store it in a vector or something like that.

func get_min_max(arr):
	arr.sort()
	return Vector2(arr[0], arr[arr.size()-1])
:bust_in_silhouette: Reply From: Hesiris

All arrays have methods called max() and min(), which return either desired value or null, if not all of the elements are of comparable types. E.g.

[1, 2, 3].max()        # returns 3
['1', '2', '3'].min()  # returns '1'
[1, '2' ,3].max()      # returns null
[].min()               # returns null

is there a way to get the index of the biggest/smallest number(besides having to find() it with the value)?

zen3001 | 2021-02-17 20:05