I've come across this problem a few times now and I don't have a nice solution for it.
Suppose I have a simple array of numbers at non-fixed intervals, myArray
. I would like to have a function that can take a whole number (it could be negative) and return the value in the array that it is closest to. In my example, I'd like it to return 850
.
I think I need to use the upper
and lower
variables to work out which of the array values is closest to the value I pass in.
Am I on the right track or is there a more efficient way of achieving this and could anyone give me a nudge in the right direction?
Here is what I have so far:
var myArray = [0,850,1800,2500,3300];
function snapTo(value){
var upper = -1;
var lower = -1;
// if the value is bigger than the last array value
if(value > myArray[myArray.length-1]){
upper = myArray[myArray.length-1];
lower = myArray[myArray.length-2];
// if the value is smaller than the first array value
} else if(value < myArray[0]){
upper = myArray[1];
lower = myArray[0];
} else {
for(var i = 0, i < myArray.length, i++){
if(value > myArray[i]){
upper = myArray[i];
lower = myArray[i-1];
break;
}
}
}
// x being the index of the closest array value to the one passed in
return myArray[x];
}
snapTo(1200);