
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 ] ]
- Related Articles
- Finding nearest Gapful number in JavaScript
- Finding nearest prime to a specified number in JavaScript
- Summing up digits and finding nearest prime in JavaScript
- JavaScript: Finding nearest prime number greater or equal to sum of digits - JavaScript
- Finding if three points are collinear - JavaScript
- Find K Closest Points to the Origin in C++
- Nearest palindrome in JavaScript
- Finding distance between two points in a 2-D plane using JavaScript
- Nearest Prime to a number - JavaScript
- Distance to nearest vowel in a string - JavaScript
- Rounding off numbers to some nearest power in JavaScript
- How to round up to the nearest N in JavaScript
- Finding Gapful number in JavaScript
- Finding perfect numbers in JavaScript
- How to round the decimal number to the nearest tenth in JavaScript?

Advertisements