根據給定點按升序距離排序點陣列 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),依此類推。

更新於:2020年8月24日

1K+ 次檢視

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.