How to find the coordinate that is closest to the point of origin?

后端 未结 2 1617
滥情空心
滥情空心 2020-12-06 14:42

I know there are many many questions about sorting javascript arrays by multiple values, but none of the answers solved my problem.

I have an array of coordinates li

相关标签:
2条回答
  • 2020-12-06 15:12

    Calculate the distance of each point using

    Math.sqrt( Math.pow(x, 2) + Math.pow(y, 2) );
    

    Take the result that's the lowest


    var points = [
      {x: 10, y: 20},
      {x: 12, y: 18},
      {x: 20, y: 30},
      {x: 5, y: 40},
      {x: 100, y: 2}
    ];
    
    function d(point) {
      return Math.pow(point.x, 2) + Math.pow(point.y, 2);
    }
    
    var closest = points.slice(1).reduce(function(min, p) {
      if (d(p) < min.d) min.point = p;
      return min;
    }, {point: points[0], d:d(points[0])}).point;
    
    closest;
    // {x: 12, y:18}
    

    You'll notice that we're skipping the Math.sqrt step here. As Mark Setchell points out, calculating the square root is a sort of "lowest common denominator" operation; We can still determine the closest point by getting the smallest x^2 + y^2 value.

    0 讨论(0)
  • 2020-12-06 15:16

    For each x,y pair, square x, square y and add together. Smallest number is nearest to the origin.

    0 讨论(0)
提交回复
热议问题