最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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];
发布评论

评论列表(0)

  1. 暂无评论