Javascript 在成对数组中查找最近数对的最快方法是什么

Javascript 在成对数组中查找最近数对的最快方法是什么,javascript,arrays,sorting,closest,closest-points,Javascript,Arrays,Sorting,Closest,Closest Points,在成对数组中查找数学上最接近的数字对的最快方法是什么。迭代所有元素,切换最短的元素并在末尾返回: 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] 函数findClosestPai

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

迭代所有元素,切换最短的元素并在末尾返回:

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]
函数findClosestPair(元素、搜索元素){
var最短距离、最短距离指数;
元素。forEach((el,索引)=>{
距离=Math.sqrt(Math.pow(el[0]-search_元素[0],2)+Math.pow(el[1]-search_元素[0],2));
if(最短距离===未定义的| |距离<最短距离){
最短距离=距离;
最短距离指数=指数;
}
});
返回元素[最短距离索引];
}
您可以在这里看到这项工作=>

您可以使用并返回具有所有对中最小增量的元组

函数findClosestPair(元素,搜索){
返回元素。减少(函数(a,b){
函数getDelta(v,w){
返回Math.abs(v[0]-w[0])*Math.abs(v[1]-w[1]);
}                
返回getDelta(a,search)log(findClosestPair(元素,搜索元素))
你说的是元素“对”,但是你的数组中有三个元素
[3531231,33.2232]
[321113,34.5433]
定义“最近的”有多种“数学”方法来测量数字对之间的距离。你想用哪一个?
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];
}