简体   繁体   中英

I have a number and I would like to get the closest number less than and closest number greater than inside a jquery array

So i have array of numbers [0, 245, 678, 978, 1647] and would like to get the closest number less than and the closest number greater than my variable. So if my variable is say 412 i would like 245 returned and 678 returned separately.

Thanks.

Something like this should do that

function closest(arr, numb) {
    var o = {
        max : Math.max.apply(null, arr), 
        min : Math.min.apply(null, arr)
    };

    arr.forEach(function(itm) {
        if (itm > numb && itm < o.max) o.max = itm;
        if (itm < numb && itm > o.min) o.min = itm;
    });

    return o;
}

to be used as

closest([0, 245, 678, 978, 1647], 412); // returns {max : 678, min : 245}

FIDDLE

It starts with the lowest and highest numbers in the array, then it iterates to see if there is a number that is higher than the passed in number, and at the same time lower than the max number, and as it updates the max number while iterating you end up with whatever is closest to the passed in value etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM