在 JavaScript 中查找距离原点最近的点

javascriptweb developmentfront end technology

问题

我们需要编写一个 JavaScript 函数,该函数将坐标数组 arr 作为第一个参数,将数字 num 作为第二个参数。

我们的函数应该查找并返回距离原点 (0, 0) 最近的 num 个点。

(此处,平面上两点之间的距离是欧几里得距离。)

例如,如果函数的输入是 −

const arr = [[3,3],[5,-1],[-2,4]];
const num = 2;

那么输出应该是 −

const output = [[3,3],[-2,4]];

示例

其代码为 −

const arr = [[3,3],[5,-1],[-2,4]];
const num = 2;
const closestPoints = (arr = [], num = 1) => {
   arr.sort(([a, b], [c, d]) => {
      return Math.sqrt(a * a + b * b) - Math.sqrt(c * c + d * d);
   });
   return arr.slice(0, num);
};
console.log(closestPoints(arr, num));

输出

控制台中的输出将是 −

[ [ 3, 3 ], [ -2, 4 ] ]

相关文章