You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取2D平面上某点到位置对象数组的最近点

如何找到数组中距离指定起点最近的位置点

你需要从位置对象数组里找出距离指定起点最近的点,示例场景如下:

// 位置数组
let locations=[
  { x_axis:900, y_axis:900, },
  { x_axis:800, y_axis:800, },
  { x_axis:10, y_axis:40,   },
  { x_axis:700, y_axis:700, },
];

// 起点
let startPoint={ x_axis:0, y_axis:0, }

function closest(locations,startPoint){
  // 需要返回最近的点:{ x_axis:10, y_axis:40 }
}

你之前尝试的代码存在逻辑和语法问题:findIndex仅接受一个回调函数,且你的条件写法不符合JS语法,无法正确筛选出最近点:

const index_0 = locations.findIndex(
  // 无效逻辑:尝试筛选坐标差在100以内的点,但语法和逻辑均错误
  item => item.x_axis - person[w].x_axis > -100,
  item => item.x_axis > person[w].x_axis <  100,

  item => item.y_axis - person[w].y_axis > -100,
  item => item.y_axis > person[w].y_axis <  100,
);
console.log(locations[index_0])

正确实现思路

找到最近点的核心是计算每个点到起点的距离,再筛选出距离最小的点。为提升效率,可直接用距离平方代替实际距离(平方根不影响大小比较),省去开根号运算。

完整实现代码

function closest(locations, startPoint) {
  // 处理空数组边界
  if (locations.length === 0) return null;

  // 初始化最小距离平方和最近点
  let minDistanceSquared = Infinity;
  let closestPoint = locations[0];

  // 遍历所有位置点
  for (const point of locations) {
    // 计算坐标差
    const xDiff = point.x_axis - startPoint.x_axis;
    const yDiff = point.y_axis - startPoint.y_axis;
    // 计算距离平方(无需开根号)
    const distanceSquared = xDiff * xDiff + yDiff * yDiff;

    // 更新最小距离和对应点
    if (distanceSquared < minDistanceSquared) {
      minDistanceSquared = distanceSquared;
      closestPoint = point;
    }
  }

  return closestPoint;
}

// 测试调用
console.log(closest(locations, startPoint)); // 输出:{ x_axis: 10, y_axis: 40 }

代码说明

  • 距离平方计算:xDiff * xDiff + yDiff * yDiff 等价于两点距离的平方,省去开根号操作,计算更快且不影响大小判断。
  • 遍历比较:逐个检查每个点,实时更新当前最小距离对应的点,遍历结束后得到结果。
  • 边界处理:先判断数组是否为空,避免空数组导致的报错。

内容的提问来源于stack exchange,提问作者Felix Gorczany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 04:40:29