admin管理员组文章数量:1356284
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
2 Answers
Reset to default 10I 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; }
本文标签: javascriptSort array of points by ascending distance from givenStack Overflow
版权声明:本文标题:javascript - Sort array of points by ascending distance from given - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743973585a2570789.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论