I am using the following code to find the closest value in an array.
var x=[0,1,2,3,4,5];
var pointX=1.5;
$.each(x, function() {
if (closest == null || Math.abs(this - pointX) < Math.abs(closest - pointX)) {
closest = this;
}
});
This will return 2.
Now consider the following scenario:
var x=[20,21,22,23,24,25]
var pointX=1.5
For this case it returns 20, but I don't want it to because 1.5 is not in the range (20-25). It should instead return null in this case. How can I do this?
null? Or should it return null (because it's not within the min and max value) but is instead returning 20?