我需要你的帮助!我有一个已知坐标的点,例如{x:5, y:4}和代表每个点的对象数组:
[{x:2,y:6},{x:14,y:10},{x:7,y:10},{x:11,y:6},{x:6,y:2}]
Run Code Online (Sandbox Code Playgroud)
现在,我需要按与给定点的距离以升序对数组进行排序,例如:
[{x: 6, y: 2}, {x: 2, y: 6}, {x: 7, y: 10}, {x: 11, y: 6}, {x: 14, y: 10}]
Run Code Online (Sandbox Code Playgroud)
我如何用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);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}Run Code Online (Sandbox Code Playgroud)