Created
March 30, 2019 13:46
-
-
Save julioxavierr/eb2042800fdba1ffac1fb936e0414edf to your computer and use it in GitHub Desktop.
Find closest point in a Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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