Skip to content

Instantly share code, notes, and snippets.

@julioxavierr
Created March 30, 2019 13:46
Show Gist options
  • Save julioxavierr/eb2042800fdba1ffac1fb936e0414edf to your computer and use it in GitHub Desktop.
Save julioxavierr/eb2042800fdba1ffac1fb936e0414edf to your computer and use it in GitHub Desktop.
Find closest point in a Array
// num - number you're looking for
// pointArr - your array of points
// coordIdx - index of the coordinate you're searching for in the point
const closestPoint = (num, pointArr, coordIdx) => {
let mid;
let left = 0;
let right = pointArr.length - 1;
while (right - left > 1) {
mid = Math.floor((left + right) / 2);
if (pointArr[mid][coordIdx] < num) {
left = mid;
} else {
right = mid;
}
}
if (num - pointArr[left][coordIdx] <= pointArr[right][coordIdx] - num) {
return left;
}
return pointArr[right];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment