Sle*_*vin 2 javascript arrays google-maps coordinates coordinate-systems
我知道有很多关于按多个值排序javascript数组的问题,但没有一个答案解决了我的问题.
我有一个坐标数组,如:
x | y
--------
10 20
12 18
20 30
5 40
100 2
Run Code Online (Sandbox Code Playgroud)
如何获得最接近原点的坐标?
Tha*_*you 14
使用计算每个点的距离
Math.sqrt( Math.pow(x, 2) + Math.pow(y, 2) );
Run Code Online (Sandbox Code Playgroud)
取最低的结果
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}
Run Code Online (Sandbox Code Playgroud)
你会注意到我们正在跳过这Math.sqrt一步.正如Mark Setchell指出的那样,计算平方根是一种"最小公分母"运算; 我们仍然可以通过获得最小值来确定最近点x^2 + y^2.