Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jquery, how would i find the closest match in an array, to a specified number

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

like image 606
brent white Avatar asked Aug 24 '10 21:08

brent white


People also ask

How do you find the closest value in an array?

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.

How does closest work in jQuery?

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.

How do I find the closest number in Javascript?

Therefore, to find out the closest number we just return the index of the found minimum in the given array indexArr. indexOf(min) .


1 Answers

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;
  }
});
like image 163
Guffa Avatar answered Sep 29 '22 20:09

Guffa