我需要你的帮助! 我有一个已知坐标的点,例如{x:5, y:4}和每个代表点的对象数组:
{x:5, y:4}
[{x:2,y:6},{x:14,y:10},{x:7,y:10},{x:11,y:6},{x:6,y:2}]
现在我需要按距给定点的距离按升序对数组进行排序,例如:
[{x: 6, y: 2}, {x: 2, y: 6}, {x: 7, y: 10}, {x: 11, y: 6}, {x: 14, y: 10}]
我怎样才能用JS做到这一点??? 谢谢!
我认为,这可能有效:
//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; }