Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm going to maintain your current code and not optimize it.</p> <pre><code>function getClosestToZero(set) { if(0 === set.length) return null; // you are assigning the actual value to the closest variable var closest = set[0], result = 0; for(var i in set) { // you are assigning the actual value to the next variable var next = set[i]; // you are comparing the absolute values if(Math.abs(closest) &gt; Math.abs(next)) { result = i; // but you are assigning the actual value closest = next; } } // thus your return value is the actual number and not its absolute return closest; } </code></pre> <p><a href="http://jsfiddle.net/N4HLT/" rel="nofollow">http://jsfiddle.net/N4HLT/</a></p> <p>You can use the isNaN() function to test whether an entry is not a number or perhaps typeof next == "number" might be more appropriate should you not desire boolean and string numerical values for instance (e.g. "2", false will ARE numbers according to the isNaN test)</p> <p><strong>UPDATED</strong></p> <pre><code>function getClosestToZeroWithNaN(set) { var closest; if(set instanceof Array) { for(var i = 0; i &lt; set.length; i++) { var val = set[i]; if(!isNaN(val)) { val = Number(val); var absVal = Math.abs(val); if(typeof closest == 'undefined' || Math.abs(closest) &gt; absVal) { closest = val; } } } } return closest; } function getClosestToZeroOnlyNumbers(set) { var closest; if(set instanceof Array) { for(var i = 0; i &lt; set.length; i++) { var val = set[i]; if(typeof val == "number") { var absVal = Math.abs(val); if(typeof closest == 'undefined' || Math.abs(closest) &gt; absVal) { closest = val; } } } } return closest; } </code></pre> <p><a href="http://jsfiddle.net/hB2T8/" rel="nofollow">http://jsfiddle.net/hB2T8/</a> look at how NaN version treats null, false and "2.12"</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload