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

Time:10-17

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

CodePudding user response:

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));

  • Related