using jquery, how would i find the closest match in an array, to a specified number
11,098
You can use the jQuery.each
method to loop the array, other than that it's just plain Javascript. Something like:
var theArray = [ 1, 3, 8, 10, 13 ];
var goal = 4;
var closest = null;
$.each(theArray, function(){
if (closest == null || Math.abs(this - goal) < Math.abs(closest - goal)) {
closest = this;
}
});
Author by
brent white
Updated on June 12, 2022Comments
-
brent white almost 2 years
using jquery, how would i find the closest match in an array, to a specified number
For example, you've got an array like this:
1, 3, 8, 10, 13, ...
What number is closest to 4?
4 would return 3
2 would return 3
5 would return 3
6 would return 8ive seen this done in many different languages, but not in jquery, is this possible to do simply