How to find the coordinate that is closest to the point of origin?
11,824
Solution 1
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.
Solution 2
For each x,y
pair, square x, square y and add together. Smallest number is nearest to the origin.
Author by
Slevin
Updated on June 04, 2022Comments
-
Slevin almost 2 years
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?
-
Mark Setchell almost 10 yearsThere's no need for the square root. If a^2 > b^2 it follows that a>b.
-
Mulan almost 10 yearsTrue, thanks for the feedback. I will update my answer.
-
Mark Setchell almost 10 years@naomik That is the Manhattan distance and it is used for some applications - I don't know if it is applicable here.
-
Mark Setchell almost 10 yearsThinking about it, the Manhattan distance is not applicable here because it will make the point 2,0 the same distance (2) from the origin as 1,1 which is obviously nearer at squareroot(2).
-
Jaanus over 6 yearsYou are not setting the min.d if d(p) < min.d, you just update the point coordinates, but distance stays old.