最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sort array of points by ascending distance from given - Stack Overflow

programmeradmin5浏览0评论

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!

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!

Share Improve this question edited May 20, 2019 at 15:21 Maheer Ali 36.6k7 gold badges49 silver badges82 bronze badges asked May 20, 2019 at 15:20 user11528936user11528936 534 bronze badges 3
  • There is good information in the MDN documentation – Matt Ellen Commented May 20, 2019 at 15:21
  • What is given point in above case? – Maheer Ali Commented May 20, 2019 at 15:22
  • How do you calculate the distance? – brk Commented May 20, 2019 at 15:22
Add a ment  | 

2 Answers 2

Reset to default 10

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

This is a slightly shorter version without using Math.sqrt, because it uses the quadratic sum of the deltas.

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

发布评论

评论列表(0)

  1. 暂无评论