Javascript find closest number in array without going over - Stack Overflow

How can I modify this very nice function to find the closest number but never higher than the input?fun

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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

You 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

相关推荐

  • Javascript find closest number in array without going over - Stack Overflow

    How can I modify this very nice function to find the closest number but never higher than the input?fun

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信