I think what I want is pretty simple but I can't really find the correct solution.
I have this kind of array in Javascript :
[0, 38, 136, 202, 261, 399]
And I get a generated value from 0 to 600 on a button click. What I need is to find the nearest lower value in this array.
For example, if the generated value is 198, I want to get 136 as the result. If the generated value is 300, I want 261... If it's 589, I want 399 etc etc.
Until now, I have tried with this code :
var theArray = [ 1, 3, 8, 10, 13 ];
var goal = 7;
var closest = null;
$.each(theArray, function(){
if (closest == null || Math.abs(this - goal) < Math.abs(closest - goal)) {
closest = this;
}
});
alert(closest);
But it only returns the closest value... Now I need the to get only the closest smaller value for the given number... How can I improve my algorithm to fit my needs?
Thanks!