Good afternoon, help me find the closest element on the page using javascript. Now I find the nearest element only in X. A bot whose 75 score will run upwards is because X is closer to it, but in fact a completely different element is closer on the page (the one that is to the right). Here is the code:

const closest = (a,g) => a.reduce((p,c) => Math.abs(cg) < Math.abs(pg) ? c : p); let botPositionX = parseInt(64); let botPositionY = parseInt(64); const data = [{x: 500, y: 285}, {x: 200, y: 324}, {x: 700, y: 200}]; const dataX = [500, 200, 700]; const dataY = [285, 324, 200]; const rightOrLeft = closest(dataX, botPositionX); const topOrBottom = closest(dataY, botPositionY); let found = data.find((loc) => { return loc.x === rightOrLeft; }); let coinPosX = parseInt(found.x); let coinPosY = parseInt(found.y); 

enter image description here

    1 answer 1

    You need to look for the distance in a straight line, taking into account the position of X and Y. The formula for finding the length of the coordinates: the длина отрезка² = (y2 - y1)² + (x2 - x1)² On JS it looks like this:

     var g = (Math.pow(x2-x1,2))+(Math.pow(y2-y1,2)); var dlina = Math.sqrt(g); 
    • In principle, it is clear that I found the lowest value, but how can we now see which key with {x, y} is the minimum value? - Puvvl
    • Where do you store the key coordinates? Use add. object, with coordinates, where all coordinates will be recorded - Dmytryk
    • const data = [{x: 500, y: 285}, {x: 200, y: 324}, {x: 700, y: 200}]; - Puvvl
    • Write a function that will alternately find the distance and write data to the intermediate array or object. Then use less ... - Dmytryk