如何找到离原点最近的坐标? [英] How to find the coordinate that is closest to the point of origin?
本文介绍了如何找到离原点最近的坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道有很多关于按多个值对 javascript 数组进行排序的问题,但没有一个答案能解决我的问题.
I know there are many many questions about sorting javascript arrays by multiple values, but none of the answers solved my problem.
我有一个坐标数组,例如:
I have an array of coordinates like:
x | y
--------
10 20
12 18
20 30
5 40
100 2
如何获取离原点最近的坐标?
How can I get the coordinate that is closest to the point of origin?
推荐答案
使用
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
值来确定最近的点.
You'll notice that we're skipping the Math.sqrt
step here. As Mark Setchell points out, calculating the square root is a sort of "lowest common denominator" operation; We can still determine the closest point by getting the smallest x^2 + y^2
value.
这篇关于如何找到离原点最近的坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文