Sort array of points by ascending distance from a given point JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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 −

$S=\sqrt{((x2-x1)^2+(y2-y1)^2)}$

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.

Published on 24-Aug-2020 09:33:45