根据给定点按升序距离排序点数组 JavaScript
假设我们有一个对象数组,每个对象都正好有两个属性 x 和 y,它们表示一个点的坐标。我们必须编写一个函数,该函数接收此数组和一个具有点 x 和 y 坐标的对象,并且我们必须根据距给定点(从最近到最远)的距离对数组中的点(对象)进行排序。
距离公式
这是一个数学公式,它指出二维平面中两点 (x1, y1) 和 (x2, y2) 之间的最短距离由下式给出:
$S=\sqrt{((x2-x1)^2+(y2-y1)^2)}$
我们将使用此公式计算每个点到给定点的距离,并根据该距离对其进行排序。
示例
const coordinates =
[{x:2,y:6},{x:14,y:10},{x:7,y:10},{x:11,y:6},{x:6,y:2}];
const distance = (coor1, coor2) => {
const x = coor2.x - coor1.x;
const y = coor2.y - coor1.y;
return Math.sqrt((x*x) + (y*y));
};
const sortByDistance = (coordinates, point) => {
const sorter = (a, b) => distance(a, point) - distance(b, point);
coordinates.sort(sorter);
};
sortByDistance(coordinates, {x: 5, y: 4});
console.log(coordinates);输出
控制台中的输出将为:
[
{ x: 6, y: 2 },
{ x: 2, y: 6 },
{ x: 7, y: 10 },
{ x: 11, y: 6 },
{ x: 14, y: 10 }
]这实际上是正确的顺序,因为 (6, 2) 最接近 (5,4),然后是 (2, 6),然后是 (7, 10),依此类推。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP