Skip to content
Advertisement

Finding closest number to 0

I have an array of integers, and I need to find the one that’s closest to zero (positive integers take priority over negative ones.)

Here is the code I have so far:

JavaScript

Currently I’m getting a result of -2 but I should be getting 2. What am I doing wrong?

Advertisement

Answer

Sort the array (add one line of code) so the last number you pick up will be positive if the same absolute value is selected for a positive and negative numbers with the same distance.

Source code:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement