按距给定的升序距离对点数组进行排序

2024-03-16

我需要你的帮助! 我有一个已知坐标的点,例如{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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按距给定的升序距离对点数组进行排序 的相关文章

随机推荐