How can I modify this very nice function to find the closest number but never higher than the input?
function closest(arr, closestTo){
var closest = Math.max.apply(null, arr);
for(var i = 0; i < arr.length; i++){
if(arr[i] >= closestTo && arr[i] < closest) closest = arr[i];
}
return closest;
}
console.log(closest(myArray, 1234));
Any help appreciated
How can I modify this very nice function to find the closest number but never higher than the input?
function closest(arr, closestTo){
var closest = Math.max.apply(null, arr);
for(var i = 0; i < arr.length; i++){
if(arr[i] >= closestTo && arr[i] < closest) closest = arr[i];
}
return closest;
}
console.log(closest(myArray, 1234));
Any help appreciated
Share Improve this question asked Oct 23, 2015 at 19:20 M. El-SetM. El-Set 7634 gold badges11 silver badges16 bronze badges2 Answers
Reset to default 5You could remove the part that checks for greater. Another method would be: remove higher values, and get max from remaining ones:
function closest(arr,val){
return Math.max.apply(null, arr.filter(function(v){return v <= val}))
}
console.log(closest([1,22,121223],24)) // prints 22
remove the greater than
parator:
if(arr[i] == closestTo && arr[i] < closest) closest = arr[i];
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744713555a4589484.html
评论列表(0条)