Finding points nearest to origin in JavaScript

Problem

We need to write a JavaScript function that takes an array of coordinates and a number as arguments. The function should find and return the specified number of closest points to the origin (0, 0) using Euclidean distance.

The Euclidean distance between a point (x, y) and the origin is calculated as: ?(x² + y²)

Example Input and Output

For the input:

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

The expected output should be:

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

Solution Using Sort and Slice

The most straightforward approach is to sort the points by their distance from the origin, then take the first num elements:

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

How It Works

Let's break down the distance calculations for each point:

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

points.forEach(([x, y]) => {
    const distance = Math.sqrt(x * x + y * y);
    console.log(`Point [${x},${y}]: distance = ${distance.toFixed(2)}`);
});
Point [3,3]: distance = 4.24
Point [5,-1]: distance = 5.10
Point [-2,4]: distance = 4.47

The sorting arranges points in ascending order by distance: [3,3] (4.24), [-2,4] (4.47), [5,-1] (5.10)

Optimized Solution

We can avoid computing square roots since we only need to compare distances:

const closestPointsOptimized = (arr = [], num = 1) => {
    // Create a copy to avoid modifying original array
    const points = [...arr];
    
    points.sort(([a, b], [c, d]) => {
        // Compare squared distances (avoids sqrt calculation)
        return (a * a + b * b) - (c * c + d * d);
    });
    
    return points.slice(0, num);
};

const testArr = [[3,3],[5,-1],[-2,4]];
console.log(closestPointsOptimized(testArr, 2));
[ [ 3, 3 ], [ -2, 4 ] ]

Key Points

  • Euclidean Distance: ?(x² + y²) from origin to point (x, y)
  • Optimization: Compare squared distances instead of actual distances
  • Array Preservation: Use spread operator to avoid modifying the original array
  • Time Complexity: O(n log n) due to sorting

Conclusion

This solution efficiently finds the closest points to the origin by sorting based on Euclidean distance. The optimized version avoids expensive square root calculations while maintaining the same result.

Updated on: 2026-03-15T23:19:00+05:30

715 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements