wonderbeyond
1/15/2017 - 8:34 AM

get closest number out of array

get closest number out of array

// Refer: http://stackoverflow.com/questions/8584902/get-closest-number-out-of-array

// closest([4, 9, 15, 6, 2], 11) == 9
function closest(arr, num) {
    return arr.reduce((prev, curr) => Math.abs(curr - num) < Math.abs(prev - num) ? curr : prev);
}