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



Let's go for a JS one liner 😉

nums.sort((a, b) => Math.abs(given_num - a) - Math.abs(given_num - b))[0]

This causes the original array to have its order changed but I don't think that's against the rules 😅


I dont think use sort is good idea:
Let see:


By including a function to sort by I'm no longer doing an alphabetical sort, which means this problem no longer exists.

  (4) [2, 3, 4, 11]

The sort() method sorts the elements of an array in place and returns the array. The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.


yes, by including compareFunction callback, we can solve this problem.


If it outputs the closest number, it works! :)

code of conduct - report abuse