Thursday, April 27, 2006

Finding The Closest Value To X In An Array

For a project I'm working on I needed to find the value in a lookup table that was closest to whatever value I put in. I wrote a simple little prototype that does the job nice and easy, it even returns both the closest value and the index of the element containing that value.

Array.prototype.findNearest = function(compare:Number):Object{
var c:Object = {value:null, index:null};
var d:Number = Infinity; //difference between this[i] and find
var t:Number;

for(var i:Number = 0; i < this.length; i++){

t = Math.abs(this[i]-compare);

if(t < d){

d = t;
c.value = this[i];
c.index = i;

return c;

To call it all you need to do is this.

var myArray:Array = [10, -55, 28, 32, -11, 63, 3];
var find:Number = 5;
var result:Object = myArray.findNearest(5);

for(var i in result){
trace(i+" "+result[i]);

Simple and effective.


Post a Comment

<< Home