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

10
задан brent white 24 August 2010 в 21:41
поделиться

2 ответа

Вы можете использовать метод jQuery.each для зацикливания массива, в остальном это обычный Javascript. Что-то вроде:

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;
  }
});
39
ответ дан 3 December 2019 в 13:54
поделиться

Вот обобщенная версия, взятая из: 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;
0
ответ дан 3 December 2019 в 13:54
поделиться
Другие вопросы по тегам:

Похожие вопросы: