- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

$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.

- Related Questions & Answers
- Get n numbers from array starting from given point JavaScript
- C program to sort a given list of numbers in ascending order using Bubble sort
- Sort by index of an array in JavaScript
- Sort array by month-year JavaScript
- How to sort an object in ascending order by the value of a key in JavaScript?
- Pick points from array such that minimum distance is maximized in C++
- Sort array of objects by string property value - JavaScript
- Sort Array of objects by two properties in JavaScript
- Sort array by year and month JavaScript
- Program to sort a given linked list into ascending order in python
- Sort array of objects by string property value in JavaScript
- Sort an array of objects by multiple properties in JavaScript
- How to sort Java array elements in ascending order?
- Sort nested array containing objects ascending and descending according to date in JavaScript
- Python program to sort the elements of an array in ascending order