Given a set of coordinates [x,y][]. For example, [[0,0], [5,10]....], how do I find the nearest N coordinates given a point? nearest(point, coordinates, N)
The idea is to do some geometric analysis.
const coordinates = [[0,0], [0,1], [0,2], [50,50], [65, 50]]
function distance(p, q) {
return Math.sqrt(Math.pow(q[0] - p[0], 2) + Math.pow(q[1] - p[1], 2))
}
function nearestNCoordinates(point, points, n) {
const closestNCoordinates = []
let cur = point
for(i=0; i<n; i++) {
const closest = points.filter(point => point[0] != cur[0] && point[1] != cur[1]).reduce((a, b) => distance(a, cur) < distance(b, cur) ? a : b);
console.log(cur, closest)
cur = closest
closestNCoordinates.push(closest)
}
return closestNCoordinates
}
My current code doesn't really work. It returns replicate datapoints and the result is not accurate.
For example, nearestNCoordinates([0,0], coordinates, 3) will return [[50,50], [0,2], [50,50]], but I expect [[0,1], [0,2], [50,50]] because based on the distances. Those 3 points are closest to [0,0].