I think I want it quite simple, but I can not find the right solution.
I have such an array in Javascript:
[0, 38, 136, 202, 261, 399]
And I get the generated value from 0 to 600 when the button is clicked. I need to find the nearest lower value in this array.
For example, if the generated value is 198, I want to get the result 136. If the generated value is 300, I want 261 ... If it is 589, I want 399, etc. Etc.
So far 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 to get only the closest lower value for a given number ... How can I improve my algorithm according to my needs?
Thanks!
source share