We're a place where coders share, stay up-to-date and grow their careers.
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.
nums
nums = [100, 200, 400, 800, 1600, 3200, 6400, 128000];
given_num = 900
Here is my solution:
Usage:
Result:
Be careful that
...
can cause a range error:RangeError: Maximum call stack size exceeded
when the
nums
array is very large.