Javascript 查找数组中最近的点

Javascript 查找数组中最近的点,javascript,arrays,object,iterator,pythagorean,Javascript,Arrays,Object,Iterator,Pythagorean,我试图找到的不仅仅是最近的点,而是由5个对象点组成的数组中的3个最近的点。我试过几个实验,每个点只使用一个距离(d)变量。但我不知道如何迭代每个点,使用毕达哥拉斯定理/距离公式将其与其他点进行比较,然后找到最接近的3。如果数组有5个点,我猜我需要使用距离(d)值将每次迭代的结果存储在一个数组中,按距离值排序,然后删除新数组中的最后一项。以下是阵列: var points = [ { id: 1, x: 0.0, y: 0.0 }, { id: 2, x: 10.1, y: -10.

我试图找到的不仅仅是最近的点,而是由5个对象点组成的数组中的3个最近的点。我试过几个实验,每个点只使用一个距离(
d
)变量。但我不知道如何迭代每个点,使用毕达哥拉斯定理/距离公式将其与其他点进行比较,然后找到最接近的3。如果数组有5个点,我猜我需要使用距离(
d
)值将每次迭代的结果存储在一个数组中,按距离值排序,然后删除新数组中的最后一项。以下是阵列:

 var points = [
   { id: 1, x: 0.0, y: 0.0 },
   { id: 2, x: 10.1, y: -10.1 },
   { id: 3, x: -12.2, y: 12.2 },
   { id: 4, x: 38.3, y: 38.3 },
   { id: 5, x: 79.0, y: 179.0 },
 ]; 
我有一个函数,根据距离的
d
键值查找最近的3个点:

 function closest(n, { id, d }) {
    return points
      .filter(o => o.id !== id)
      .sort((a, b) => Math.abs(a.d - d) - Math.abs(b.d - d))
      .slice(0, n);
 };
我有一种方法可以应用这个函数并将结果记录到控制台中,这样它就可以打印“ID:1stClosest,2ndClosest,3rdClosest”:

现在,我只是尝试迭代每个点,应用距离公式来获得每个点比较的d:值,将其推到一个新数组中,我假设并应用上面的部分(
result
最近的
函数)。我该怎么做?以下是我目前掌握的情况:

 points.forEach((item) => {
  var newArray = [item];
  var pt = null;
  var d = null;
  for (var i = 0; i < points.length; i = i + 1) {
      //compare this point with all of the other points
      for (var j = i + 1; j < points.length; j = j + 1) {
          //compute distance
          var curr = Math.sqrt(Math.pow(points[i][0] - points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2));
      //get the distance between each point and push to a new array
          if (d === null || curr < d) {
            o = points.id[i];
            pt = points.id[j];
            d = curr;
          }
       }
     }
  newArray.push = {
   "id": o,
   "pt": pt,
   "d": d
  };
  console.log(newArray);
});
points.forEach((项目)=>{
var newArray=[item];
var-pt=null;
var d=null;
对于(变量i=0;i
如果我理解正确,这与问题类似。一种(直观但可能效率低下)方法是简单地强制集合中的项目。也就是说,对于两点,使用两个for循环。对于三个点,可以使用三个嵌套循环。然后,你会发现最大的“接近度”。我不确定你想如何定义接近度,但我认为从A到B,B到C,C到A的距离之和会很好地工作。测试点编组的每个枚举的最小“距离”将导致最接近的配对

所以,我不确定你的其他功能会在哪里发挥作用。更大的问题是如何确定“最近的”,因此调用函数来执行更大问题的子问题是不正确的

如果你想要三组最近的点,那么你需要跟踪每对点的距离,并确定你想要如何使它们彼此区别开来。即,是否允许同一点位于另一组点中

 points.forEach((item) => {
  var newArray = [item];
  var pt = null;
  var d = null;
  for (var i = 0; i < points.length; i = i + 1) {
      //compare this point with all of the other points
      for (var j = i + 1; j < points.length; j = j + 1) {
          //compute distance
          var curr = Math.sqrt(Math.pow(points[i][0] - points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2));
      //get the distance between each point and push to a new array
          if (d === null || curr < d) {
            o = points.id[i];
            pt = points.id[j];
            d = curr;
          }
       }
     }
  newArray.push = {
   "id": o,
   "pt": pt,
   "d": d
  };
  console.log(newArray);
});