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

时间:2019-05-20 15:20:03

标签: javascript arrays

我需要您的帮助! 我有一个已知坐标的点,例如{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做到这一点??? 谢谢!

2 个答案:

答案 0 :(得分:7)

我认为这可能有效:

//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;
}

答案 1 :(得分:2)

这是不使用Math.sqrt的版本,因为它使用了增量的平方和。

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; }