Given a list of coordinates, the task is to find the k closest coordinates to the origin.
While I successfully calculated the distances between the points and the origin, determining the closest k points presented an issue. To solve this, I implemented logic in a secondary for loop where I sorted the array of distances from closest to furthest, then filtered out the values less than k.
function kClosest(points, k) {
let length = [];
let arr = [];
let result = [];
let a = 0;
let b = 0;
for (let i = 0; i < points.length; i++) {
a = points[i][0]; //x coord
b = points[i][1]; //y coord (y will always be second number or '1')
length.push(parseFloat(calcHypotenuse(a, b).toFixed(4)))
arr.push([points[i], length[i]])
}
function calcHypotenuse(a, b) {
return (Math.sqrt((a * a) + (b * b)));
}
for (let i = 0; i < k; i++) {
arr = arr.sort();
result.push(arr[i][0])
}
return result;
}
console.log(kClosest([
[-5, 4],
[-6, -5],
[4, 6]
], K = 2))
Expected output: [-5, 4], [4, 6] // The initial prediction was [-5, 4], [-6, -5]