-1

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])
  • @KonradLinkowski My question is clearly on noob level javascript and you pointed me to some 3d advanced python library. Not sure if its helpful. – Felix Gorczany Oct 16 '22 at 18:42
  • Sorry, wrong link, I mean this https://stackoverflow.com/questions/20916953/get-distance-between-two-points-in-canvas – Konrad Oct 16 '22 at 18:44
  • I couldn't know which part is hard for you because both of them are basics – Konrad Oct 16 '22 at 18:50
  • @KonradLinkowski Its fine. Someone else perfectly handled the question. But your input was meaningful in some way I suppose – Felix Gorczany Oct 16 '22 at 18:53

1 Answers1

1

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));
Terry
  • 63,248
  • 15
  • 96
  • 118