Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you find the closet coordinate in the array from the target

This is the array. I want to filter the closet x and y coordinates from a target which is:

target.x = 310 and target.y = 280;

the correct value is the value in the array at number 8.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I just a filter scheme to filter the correct value from the array that’s closest to the target x and y?

distFromBall = [
{y: 10, x: 300, number: 1},
{y: 23.333333333333314, x: 75, number: 2},
{y: 23.333333333333314, x: 225, number: 3},
{y: 23.333333333333314, x: 375, number: 4},
{y: 23.333333333333314, x: 525, number: 5},
{y: 270, x: 75, number: 6},
{y: 270, x: 225, number: 7},
{y: 270, x: 375, number: 8},
{y: 270, x: 525, number: 9},
{y: 290, x: 150, number: 10},
{y: 290, x: 450, number: 11}]

i tried something like this but no luck:

    var f = distFromBall.filter(function (a,i) {
        return a.x > 0;
    });

    f.sort(function (a, b) {
        return a.x - b.x;
    });

    f.sort(function (a, b) {
        return a.y - b.y;
    });
    var num = distFromBall[0].number;

    var pl = arrayPlayerHome.find(function (a) {
        return a.shirtNumber == num;
    });

    return pl;

>Solution :

With the pythagorean theorem and .reduce, you can keep the closest number object to the target as the accumulator and return it at the end.

const getDist = (a, b) => Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
const findClosest = (target) => distFromBall
  .reduce((a, item) => getDist(item, target) < getDist(a, target) ? item : a);

const distFromBall = [
{y: 10, x: 300, number: 1},
{y: 23.333333333333314, x: 75, number: 2},
{y: 23.333333333333314, x: 225, number: 3},
{y: 23.333333333333314, x: 375, number: 4},
{y: 23.333333333333314, x: 525, number: 5},
{y: 270, x: 75, number: 6},
{y: 270, x: 225, number: 7},
{y: 270, x: 375, number: 8},
{y: 270, x: 525, number: 9},
{y: 290, x: 150, number: 10},
{y: 290, x: 450, number: 11}]

console.log(findClosest({ x: 310, y: 280 }));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading