# Finding points nearest to origin in JavaScript

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

## 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 ] ]