+3 votes

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

in Engine by (274 points)

2 Answers

+1 vote

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):
    return Vector2(arr[0], arr[arr.size()-1])
by (5,278 points)
edited by
+10 votes

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


by (34 points)

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.