js 判断 坐标[x,y,z]离数组里哪组坐标最近?

js 判断 坐标[x,y,z]离数组里哪组坐标最近?
比如:

[-11.034364525537594,1,24.978631454302235]

在下面数组里哪组最近?

[
   [-4.167605156499352,1,16.43419792128068], 
   [-13.60939928892453,1,28.216932747654095], 
   [-16.84770058227477,1,27.514650539457307]
]

谢谢大家的回答,我这里需求没有说明白,

需求:怎么确定交点[x,y,z]是在线段1的第几段线上生成?

image.png

image.png

阅读 3.2k
2 个回答

1、计算两点距离最近的可以用下面的方法

const target = [-11.034364525537594,1,24.978631454302235];
const arr = [
  [-4.167605156499352,1,16.43419792128068], 
  [-13.60939928892453,1,28.216932747654095], 
  [-16.84770058227477,1,27.514650539457307]
]
arr.reduce((res, item, index) => {
  const sum = Math.pow(item[0] - target[0], 2) + Math.pow(item[1] - target[1], 2) + Math.pow(item[2] - target[2], 2);
  if (sum < res[0] || index == 0) {
    res = [sum, index];
  }
  return res
}, [0, 0]);
//避免重复计算res[0]记录最小距离,res[1] 就是距离最近的arr中的索引值

2、根据修改后的问题,就是判断某一个点是在哪一条直线上了,这就是数学中3点共线的问题了

// 判断3点是否共线,用空间向量
function isInOneLine([x1, y1, z1], [x2, y2, z2], [x3, y3, z3]) {
  // 为避免精度问题,截取10位小数后再对比
  const fixed = num => num.toFixed(10);
  return fixed((z2-z1) * (y3-y2)) == fixed((z3-z2) * (y2-y1)) &&
    fixed((z2-z1) * (y3-y2)) == fixed((z3-z2) * (x2-x1)) &&
    fixed((y2-y1) * (y3-y2)) == fixed((y3-y2) * (x2-x1));
}
// 找到起点坐标的索引,找不到则返回-1
function findIndex(arr, point) {
  const targetIndex = -1;
  for (let i = 0; i + 1 < arr.length; i++) {
    if (isInOneLine(arr[i], arr[i+1], point)) {
      targetIndex = i;
      break;
    }
  }
  return targetIndex;
}

// test
const point = [-11.034364525537594,1,24.978631454302235];
const arr = [
  [-4.167605156499352,1,16.43419792128068], 
  [-13.60939928892453,1,28.216932747654095], 
  [-16.84770058227477,1,27.514650539457307]
]
findIndex(arr, point)

计算距离呗

function dist3d(coord1, coord2) {
  let dx = coord1[0] - coord2[0];
  let dy = coord1[1] - coord2[1];
  let dz = coord1[2] - coord2[2];
  return Math.sqrt(dx * dx + dy * dy + dz * dz)
}

let list = [
   [-4.167605156499352,1,16.43419792128068], 
   [-13.60939928892453,1,28.216932747654095], 
   [-16.84770058227477,1,27.514650539457307]
]
let target = [-11.034364525537594,1,24.978631454302235]

let result = list.reduce((res, i) => {
    let d = dist3d(target, i);
    if (d < res.dist) {
        res.dist = d;
        res.point = i
    }
    return res
}, { dist: Infinity })

console.log(result.point)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题