Find the closest number in array?

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

I have an simple array:

number_array = [6, 2, 10, 18, 11, 4, 20]
index_number = 15
result should be number_array [3]

I’m trying to return the closest number to 15. Thanks for the help!

:bust_in_silhouette: Reply From: avencherus

An algorithm comparing the differences in a loop.

A very basic idea for that would be:

extends Node2D

const INT_MAX = 2147483647

func find_closest(match, array):
	
	var best_match = null
	var least_diff = INT_MAX
	
	for number in array:
		
		var diff = abs(match - number)
		
		if(diff < least_diff):
			best_match = number
			least_diff = diff
			
	return best_match


func _ready():

	var data = [6, 2, 10, 18, 11, 4, 20]
	print(find_closest(15, data))