Search / sort multidimensional arrays

I created a multidimensional array based on x / y coordinates around the circumference of a circle. An object can be dragged in an arc (in javascript), and then "dropped" anywhere. The problem is that I need to find the nearest x and y coordinate, where the object is “dropped”.

My current solution involves looping through an array and finding the closest value to x, and then looping back to find the y coordinate, but that doesn't seem very clean, and there are problems with it.

Does anyone have any suggestions?

Thank!

+3
source share
2 answers

, . , (x, y). , . , "" .

, , ( Wikipedia, ). - , , x y, .

var findNearestPoint = function (p, points) {
  var minDist = Number.POSITIVE_INFINITY,
      minPoint = -1,
      i,
      l,
      curDist,
      sqr = function(x) { return x * x; };

  for (i = 0, l = points.length; i < l; i++) {
    curDist = sqr(p.x - points[i].x) + sqr(p.y - points[i].y);
    if (curDist < minDist) {
      minDist = curDist;
      minPoint = i;
    }
  } 
  return points[i];
};

(, .)

+1

( ), .

  • x.
  • x , y, .
    • x , ( 1).
    • x , ( 1).

y. , , . , .

0

All Articles