DEV Community

loading...

Discussion on: Challenge: Get Closest Number in an Array

Collapse
link2twenty profile image
Andrew Bone • Edited

Javascript:

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 😅

Collapse
andy profile image
Andy Zhao (he/him) Author

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

Collapse
bugb profile image
bugb • Edited

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

[2,3,4,11].sort()
Collapse
link2twenty profile image
Andrew Bone

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

  console.log([2,3,4,11].sort((a,b)=>a-b));
Output:
  (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.

developer.mozilla.org/en-US/docs/W...

Thread Thread
bugb profile image
bugb

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