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 8
ive seen this done in many different languages, but not in jquery, is this possible to do simply
Find the closest value in array using reduce() The easiest way to do this is to use Math. abs(), so lets use that. With this function we check whether the absolute value of (b – 8) is less than the absolute value of (a – 8) and then return the winner.
The closest( selector ) method works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression.
Therefore, to find out the closest number we just return the index of the found minimum in the given array indexArr. indexOf(min) .
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With