Returning the closest number in a given array

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ess_l

I’m looking for a way to find the closest value in an array based on a target.

For example:

var a = 78
var list = [0, 90, 180, 270]

closest(a, list) # returns 90 as it's the closest number to a in list

closest(-425, list) # returns 0
:bust_in_silhouette: Reply From: eod

You’d have to traverse the whole array, then I would store the closest value in a variable.

func closest(my_number:int, my_array:Array)->int:
    # Initialize
    var closest_num:int
    var closest_delta:int = 0
    var temp_delta:int = 0
    # Loop through entire array
    for i in range(my_array.size()):
        if my_array[i] == my_number: return my_array[i] # exact match found!
        temp_delta = int(abs(my_array[i]-my_number))
        if closest_delta == 0 or temp_delta < closest_delta:
        closest_num = my_array[i]
        closest_delta = temp_delta
    # Return closest number found
    return closest_num

Something like the above should get you close to what you want.