Finding points nearest to origin in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of coordinates, arr, as the first argument, and a number, num, as the second argument.

Our function should find and return the num closest points to the origin (0, 0).

(Here, the distance between two points on a plane is the Euclidean distance.)

For example, if the input to the function is −

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

Then the output should be −

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

Example

The code for this will be −

 Live Demo

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));

Output

And the output in the console will be −

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

Updated on: 09-Apr-2021

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements