Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the shortest distance from a point on 2d plane from an array of location objects

I have an array containing objects of location and want the shortest point to a different point ie

//location array
let locations=[
  { x_axis:900, y_axis:900, },
  { x_axis:800, y_axis:800, },
  { x_axis:10, y_axis:40,   },
  { x_axis:700, y_axis:700, },
];

let startPoint={ x_axis:0, y_axis:0, }

function closest(locations,startPoint){
//get closest point which is { x_axis:10, y_axis:40 }
}

What I tried using

const index_0 = locations.findIndex(
  // Trash code but my aim was to get the closest locations object
  // to mainPoint within 100 difference
  item => item.x_axis - person[w].x_axis > -100,
  item => item.x_axis > person[w].x_axis <  100,

  item => item.y_axis - person[w].y_axis > -100,
  item => item.y_axis > person[w].y_axis <  100,
);
console.log(locations[index_0])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to get the closest point on the Euclidean plane then it’s a matter of applying Pythagorean theorem, and finding the point that gives the smallest distance.

  1. Iterate through all locations
  2. Calculate the distance of each entry in locations against the start point: this can be done by simply calculating the Euclidean distance using Pythagorean theorum
  3. Find the index of the smallest distance
  4. Retrieve the entry of the point by the given index

To calculate the hypothenuse between two points, you can either use Math.hypot(x1-x2, y1-y2) or the good old way of Math.sqrt(Math.pow(x1-x2, 2), Math.pow(y1-y2,2))

See proof-of-concept below:

const locations = [{
    x_axis: 900,
    y_axis: 900,
  },
  {
    x_axis: 800,
    y_axis: 800,
  },
  {
    x_axis: 10,
    y_axis: 40,
  },
  {
    x_axis: 700,
    y_axis: 700,
  },
];

const startPoint = {
  x_axis: 0,
  y_axis: 0,
}

function closest(locations, startPoint) {
  const distances = locations.map(location => {
    return Math.hypot(startPoint.x_axis - location.x_axis, startPoint.y_axis - location.x_axis);
  });
  
  const minimumDistance = Math.min(...distances);
  const indexOfMinimumDistance = distances.indexOf(minimumDistance);
  
  return locations[indexOfMinimumDistance];
}

console.log(closest(locations, startPoint));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading