在成对数组中找到最接近的数字对的最快方法是什么

Whats fastest way for finding closest number pair in array of pairs

var element_pairs = [[11.333112,22.655543],[35,31231,33.2232],[122352,343421]];
var search_pair = [32,1113,34.5433];
findClosestPair(element_pairs, search_pair);
// [35,31231,33.2232]

在成对数组中找到数学上最接近的数字对的最快方法是什么。

遍历所有元素并切换最短的元素和return最后的元素:

function findClosestPair(elements,search_element) {
    var shortestDistance, shortestDistanceIndex;

  elements.forEach((el, index) => {
    distance = Math.sqrt(Math.pow(el[0] - search_element[0], 2) + Math.pow(el[1] - search_element[0], 2));
    if (shortestDistance === undefined || distance < shortestDistance) {
      shortestDistance = distance;
      shortestDistanceIndex = index;
    }
  });

  return elements[shortestDistanceIndex];
}

你可以在这里看到这个作品=> https://jsfiddle.net/q8738b9a/

您可以使用 Array#reduce 和 return 具有所有对中最小增量的 tupel。

function findClosestPair(elements, search) {
    return elements.reduce(function (a, b) {
        function getDelta(v, w) {
            return Math.abs(v[0] - w[0]) * Math.abs(v[1] - w[1]);
        }                
        return getDelta(a, search) < getDelta(b, search) ? a : b;
    });
}


var elements = [[11.333112, 22.655543], [35.31231, 33.2232], [122352, 343421]],
    search_element = [32.1113, 34.5433];

console.log(findClosestPair(elements, search_element));