Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 −
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 ] ]
Advertisements
