如何找到最接近原点的坐标?

时间:2014-07-16 21:23:11

标签: javascript arrays google-maps coordinates coordinate-systems

我知道有很多关于按多个值排序javascript数组的问题,但没有一个答案解决了我的问题。

我有一个坐标数组,如:

x  |  y
--------
10    20
12    18
20    30
5     40
100   2

如何获得最接近原点的坐标?

2 个答案:

答案 0 :(得分:13)

使用

计算每个点的距离
Math.sqrt( Math.pow(x, 2) + Math.pow(y, 2) );

取最低的结果


var points = [
  {x: 10, y: 20},
  {x: 12, y: 18},
  {x: 20, y: 30},
  {x: 5, y: 40},
  {x: 100, y: 2}
];

function d(point) {
  return Math.pow(point.x, 2) + Math.pow(point.y, 2);
}

var closest = points.slice(1).reduce(function(min, p) {
  if (d(p) < min.d) min.point = p;
  return min;
}, {point: points[0], d:d(points[0])}).point;

closest;
// {x: 12, y:18}

您会注意到我们正在跳过Math.sqrt步骤。正如Mark Setchell指出的那样,计算平方根是一种“最小公分母”运算;我们仍然可以通过获得最小的x^2 + y^2值来确定最近的点。

答案 1 :(得分:1)

对于每个x,y对,方x,平方y并加在一起。最小的数字最接近原点。

相关问题