Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 816
user11528936 Avatar asked Dec 13 '22 11:12

user11528936


1 Answers

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;
}
like image 165
Yevgen Gorbunkov Avatar answered Dec 31 '22 21:12

Yevgen Gorbunkov