// array = sorted array of integers // val = pivot element // dir = boolean, if true, returns the previous value function getVal(array, val, dir) { for (var i=0; i < array.length; i++) { if (dir == true) { if (array[i] > val){ return array[i-1] || 0; } } else { if (array[i] >= val) { return array[i]; } } } }
Example:
array = [0, 5, 7, 9, 22, 27]; pivot = 11; getVal(array, pivot); //returns 22 getVal(array, pivot, true); //returns 9
You can also use array.reduce to find the closest number. The only problem is that array.reduce doesn’t pass extra parameters to the callback, and you need to pass the “pivot”.
To go around this problem, you could create a class, and store the “pivot” in the instance as a property.
Here is a quick fiddle.
Also, the array doesn’t have to be sorted for this implementation.
Thank you for your thoughts and for the fiddle. It’s a very nice method.