Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

javascript - How to find the coordinate that is closest to the point of origin?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Calculate the distance of each point using

Math.sqrt( Math.pow(x, 2) + Math.pow(y, 2) );

Take the result that's the lowest


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}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...