user11528936
user11528936

Reputation: 53

Sort array of points by ascending distance from given

I need your help! I have a point with known coordinates, like {x:5, y:4} and array of objects each representing points:

[{x:2,y:6},{x:14,y:10},{x:7,y:10},{x:11,y:6},{x:6,y:2}]

Now I need to sort the array by distance from the given point in ascending order, like:

[{x: 6, y: 2}, {x: 2, y: 6}, {x: 7, y: 10}, {x: 11, y: 6}, {x: 14, y: 10}]

How can I don that with JS??? Thanks!

Upvotes: 5

Views: 1407

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386654

This is a slightly shorter version without using Math.sqrt, because it uses the quadratic sum of the deltas.

const
   array = [{ x: 2, y: 6 }, { x: 14, y: 10 }, { x: 7, y: 10 }, { x: 11, y: 6 }, { x: 6, y: 2 }],
   point = { x: 5, y: 4 };

array.sort((a, b) =>
    (a.x - point.x) ** 2 + (a.y - point.y) ** 2 -
    (b.x - point.x) ** 2 + (b.y - point.y) ** 2
);

console.log(array)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

I think, that might work:

//reference point
const a = {x:5,y:4};
//array of points to sort
const points = [{x:2,y:6},{x:14,y:10},{x:7,y:10},{x:11,y:6},{x:6,y:2}];
//squared distance
const sqDist = (pointa, pointb) => (pointa.x-pointb.x)**2+(pointa.y-pointb.y)**2;
//sorting
const res = points.sort((pointa, pointb) => sqDist(a,pointa)-sqDist(a,pointb));

console.log(res);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Upvotes: 10

Related Questions