But be aware that there can be 2 values which are the closest to newVar
.
For example:
keyVals[23] = 234;
keyVals[129] = 'aaa';
keyVals[172] = 'lolipops';
Both 23 and 129 are the closest to 76.
Then,
var keyVals = Array;
keyVals[23] = 234;
keyVals[129] = 'aaa';
keyVals[172] = 'lolipops';
newVar = 76;
var closest=new Object();
for(var i in keyVals){
if(typeof closest.dif=='undefined'){
closest.dif=Math.abs(newVar-i);
closest.val=[i];
}else{
if(closest.dif==Math.abs(newVar-i)){
closest.val.push(i);
}else if(closest.dif>Math.abs(newVar-i)){
closest.dif=Math.abs(newVar-i);
closest.val=[i];
}
}
}
alert("The closest keys to "+newVar+" are ["+closest.val.join(',')+"], with a difference of "+closest.dif);
will alert "The closest keys to 76 are [23,129], with a difference of 53"
Or with your array,
keyVals[23] = 234;
keyVals[58] = 'sunshine';
keyVals[172] = 'lolipops';
will alert "The closest keys to 76 are [58], with a difference of 18"