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
-
Economics & Finance
Sort array of points by ascending distance from a given point JavaScript
Let's say, we have an array of objects with each object having exactly two properties, x and y that represent the coordinates of a point. We have to write a function that takes in this array and an object with x and y coordinates of a point and we have to sort the points (objects) in the array according to the distance from the given point (nearest to farthest).
The Distance Formula
It is a mathematical formula that states that the shortest distance between two points (x1, y1) and (x2, y2) in a two-dimensional plane is given by ?
We will be using this formula to calculate the distance of each point from the given point and sort them according to that.
Example
const coordinates = [{x:2,y:6},{x:14,y:10},{x:7,y:10},{x:11,y:6},{x:6,y:2}];
const distance = (coor1, coor2) => {
const x = coor2.x - coor1.x;
const y = coor2.y - coor1.y;
return Math.sqrt((x*x) + (y*y));
};
const sortByDistance = (coordinates, point) => {
const sorter = (a, b) => distance(a, point) - distance(b, point);
coordinates.sort(sorter);
};
sortByDistance(coordinates, {x: 5, y: 4});
console.log(coordinates);
Output
The output in the console will be ?
[
{ x: 6, y: 2 },
{ x: 2, y: 6 },
{ x: 7, y: 10 },
{ x: 11, y: 6 },
{ x: 14, y: 10 }
]
And this is in fact the correct order as (6, 2) is nearest to (5,4), then comes (2, 6) then (7, 10) and so on.
How It Works
The algorithm works in three steps:
-
Calculate Distance: The
distance()function computes the Euclidean distance between two points using the distance formula. -
Compare Function: The
sorterfunction compares distances from each point to the reference point. -
Sort Array: JavaScript's
sort()method arranges points from nearest to farthest based on calculated distances.
Alternative Implementation
Here's a more concise version that doesn't modify the original array:
const points = [{x:2,y:6},{x:14,y:10},{x:7,y:10},{x:11,y:6},{x:6,y:2}];
const referencePoint = {x: 5, y: 4};
const sortedPoints = points
.map(point => ({
...point,
distance: Math.sqrt(Math.pow(point.x - referencePoint.x, 2) + Math.pow(point.y - referencePoint.y, 2))
}))
.sort((a, b) => a.distance - b.distance)
.map(({distance, ...point}) => point);
console.log(sortedPoints);
[
{ x: 6, y: 2 },
{ x: 2, y: 6 },
{ x: 7, y: 10 },
{ x: 11, y: 6 },
{ x: 14, y: 10 }
]
Conclusion
Sorting points by distance involves calculating Euclidean distances and using JavaScript's sort() method with a custom comparator. This technique is useful in applications like finding nearest neighbors or clustering algorithms.
