Proximity checking for number values?

Greetings all.

It’s been a while but I didn’t get to do too much flashy stuff lately so I kind of neglected the Kirupa world… but now I have another problem so of course I come crawling back :slight_smile:

I have an array with a bunch of numbers in it. No, that’s not the problem yet :smiley:

Currently, the array contains “10”, “25” and “50”.

There’s a variable number that is divided by 3 and I need to check which of the values of the array is closest to the result of the division.

Say I have the value “130”… it’s divided by 3… so the result is 43.3

Now I need to write a code that compares this value to the array values and returns the one that is closest. Is there a way to do this easily?

I’m thinking maybe take the result of the division and substract the values from the array

43.3 - 10 = 33.3
43.3 - 25 = 18.3
43.3 - 50 = -6.7

and then compare those “remains” for which one is smaller than the others…

By the way- I know I’ve done it before sometime but isn’t there a way / function to automatically make all numbers positive? I’m a bit phased out right now and can’t think of what it was. I know I could add something like “if it’s lesser than zero, multiply it with -1”… but isn’t there something that does that automatically?

Thanks, all :slight_smile:

I solved it myself- thanks for reading this anyways. I’ll post my solution later if anyone is interested.

~over.

For “the by the way” question: Its Math.abs( expression )

For the first question:
Your logic is good… to implement it try the following

function getClosest(a:Number, numbers:Array):Number {
	for (var i = 0; i<numbers.length; i++) {
		if (closest == undefined) {
			closest = [Math.abs(a-numbers*), numbers*];
		} else if (Math.abs(a-numbers*)<closest[0]) {
			closest = [Math.abs(a-numbers*), numbers*];
		}
	}
	return closest[1];
}
trace(getClosest(43.3, new Array(10, 25, 50)));

edit: lol