10

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

brent white
  • 103
  • 1
  • 1
  • 4
  • 6
    jQuery is a JavaScript library to ease DOM traversion and manipulation and doing Ajax stuff, not to do maths. For this "plain" JavaScript is namely more than suitable. Have you considered looking at JavaScript? – BalusC Aug 24 '10 at 21:43

2 Answers2

39

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;
  }
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    brilliant, works beautifully, thanks for such a quick reply, and clean code – brent white Aug 24 '10 at 23:06
  • Better check by **closest === null**, otherwise 0 == null would return true as well. – Markus Siebeneicher Aug 16 '14 at 11:02
  • @MarkusSiebeneicher: Where do you get that result? When I try it (in Firefox), `0 == null` is false. – Guffa Aug 16 '14 at 11:40
  • @Guffa: you are right, I mixed something up. After coding years with non-strict variable types, I got a bit paranoid when coding javascript. Anyway, its good practice to use === for explicit type check. In this case, it really doesnt matter. Thanks for pointing it out. – Markus Siebeneicher Aug 16 '14 at 15:21
  • closest is not a number.. I am getting this when I render closest in console `Number {[[PrimitiveValue]]: 678}` – Imran Bughio Jan 19 '16 at 14:15
  • @ImranBughio: It's a number, what you get in the console is just how that specific browser chose to display it. The `Number` object is the formal form of a numeric value in JavaScript, but browsers only create actual `Number` object instances when needed. Most of the time numbers are handled as primitive values. – Guffa Jan 19 '16 at 22:37
0

Here's a generalized version, taken from: http://www.weask.us/entry/finding-closest-number-array

int nearest = -1;
int bestDistanceFoundYet = Integer.MAX_INTEGER;
// We iterate on the array...
for (int i = 0; i < array.length; i++) {
   // if we found the desired number, we return it.
   if (array[i] == desiredNumber) {
      return array[i];
   } else {
      // else, we consider the difference between the desired number and the current number in the array.
      int d = Math.abs(desiredNumber - array[i]);
      if (d < bestDistanceFoundYet) {
         // For the moment, this value is the nearest to the desired number...
         nearest = array[i];
      }
   }
}
return nearest;
sje397
  • 41,293
  • 8
  • 87
  • 103
bryan.taylor
  • 584
  • 2
  • 9