If I have an array like this:
var array = [1, 3, 4, 5, 9, 10];
And I have a value like this:
var value = 8;
I want to get this result:
var result = getClosestValues(array, value); // [5, 9]
What's the correct/preferred way to do this in javascript? It seems like this is probably a formal algorithm somewhere. Maybe like this:
var getClosestValues = function(array, value) {
var low, high = 0, value;
for (var i = 0; i < array.length; i++) {
if (low <= value && low < array[i])
low = array[i];
if (high == value && high < array[i])
high = array[i];
};
return [low, high];
}
Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…