re: Challenge: Get Closest Number in an Array VIEW POST

VIEW FULL DISCUSSION
 

nums = [100, 200, 400, 800, 1600, 3200, 6400, 128000];
given_num = 900

Here is my solution:

f = a => (m=Math.min(...nums.map(v=>Math.abs(v-given_num))),nums.find(v=>v==given_num - m || v== m-given_num))

Usage:

f(nums)

Result:

800
 

Be careful that ... can cause a range error:

RangeError: Maximum call stack size exceeded

when the nums array is very large.

code of conduct - report abuse