используя jquery, как мне найти наиболее близкое совпадение в массиве с указанным числом - PullRequest
10 голосов
/ 25 августа 2010

используя jquery, как мне найти самое близкое совпадение в массиве с указанным числом

Например, у вас есть такой массив:

1, 3, 8, 10, 13, ...

Какое число ближе всего к 4?

4 вернет 3
2 вернет 3
5 вернется 3
6 вернется 8

Я видел, что это было сделано на разных языках, но не в jquery, это можно сделать просто

Ответы [ 2 ]

39 голосов
/ 25 августа 2010

Вы можете использовать метод 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;
  }
});
0 голосов
/ 25 августа 2010

Вот обобщенная версия, взятая из: 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;
...