DEV Community

loading...

Discussion on: Challenge: Get Closest Number in an Array

Collapse
bugb profile image
bugb • Edited

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
Collapse
lucifer1004 profile image
Gabriel Wu • Edited

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

RangeError: Maximum call stack size exceeded

when the nums array is very large.