在 JavaScript 中寻找离原点最近的点

问题

我们需要编写一个 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 ] ]

猜你喜欢