Home > Enterprise >  How do you find the closet coordinate in the array from the target
How do you find the closet coordinate in the array from the target

Time:08-07

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.

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;

CodePudding user response:

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 }));

  • Related