Lets say I have an array with numbers like this:
var a = [4, 5, 7, 9, 12, 15, 18, 19, 20, 23, 27, 31];
It is sorted in ascending order, now, let's say I pick a value x:
var x = 13;
How do I find which two values that are closest to x?
In this case it would be 12 and 15, but how do I get these two for any given x, and in case x is lower than the lowest, then only return the lowest, and if it's greater than the greatest, return only the greatest, like if x = 3, then only return one value, 4?
I have tried this:
function getClosest(a, x) {
for (var i = 0; i < a.length - 1; i++) {
var c1 = a[i],
c2 = a[i + 1];
if (x > c1 && x < c2) return [c1, c2];
else if (i == 0) return [c1];
else if (i == a.length - 2) return [c2];
}
}
Now, this is my approach, how would you solve this/what is the most efficient solution to this?