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

Remove closest points in Javascript

I have two arrays, for example, A and B. A is a master array and B is a child array. A and B both contain centroid points or x and `y’ values. I want to remove all the closest points of B from A. For more clarity, for each element of B you find the closest element in A and remove it.

Any help will be highly appreciated. I am new to JavaScript.

Please find the example below for clarity.

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

const A = [{
    x: 58,
    y: 62.60,
  },
  {
    x: 52,
    y:196,
  },
  {
    x: 167,
    y: 143.601,
  },
  {
    x:178,
    y: 183,
  },
];

const B = [{
    x: 57,
    y: 61.60,
  },
  {
    x: 50,
    y:196,
  },
];

Expected Answer:

const A = [{
        x: 167,
        y: 143.601,
      },
      {
        x:178,
        y: 183,
      },
    ];

>Solution :

Break the problem into smaller parts.

First, write a function to check the distance between 2 points.

const distance = (a, b) => {
    return Math.hypot(a.x - b.x, a.y - b.y);
};

Then write a function to find the position of the smallest distance in a list of points, given a target point.

const findClosestIndex = (list, point) => {
    const distances = list.map((listPoint) => {
        return distance(listPoint, point);
    });
    const min = Math.min(...distances);
    return distances.findIndex((p) => {
        return p === min;
    });
};

Finally, remove all the points that you want to remove.

const A = [
    { x: 58, y: 62.6 },
    { x: 52, y: 196 },
    { x: 167, y: 143.601 },
    { x: 178, y: 183 },
];

const B = [
    { x: 57, y: 61.6 },
    { x: 50, y: 196 },
];

const AWithClosestToBRemoved = B.reduce((result, point) => {
    const closestIndex = findClosestIndex(result, point);
    return result.filter((_, i) => {
        return i !== closestIndex;
    });
}, A);

Edit History

  • Changed more verbose math into Math.hypot based on suggestion in comments.
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