Created
May 9, 2013 10:34
-
-
Save jswhisperer/5546782 to your computer and use it in GitHub Desktop.
Pass an array and a value, get back the closest number.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var getClosestNum = function(num, ar) { | |
var i = 0, closestDiff, currentDiff; | |
if(ar.length) { | |
closest = ar[0]; | |
for(i;i<ar.length;i++) { | |
closestDiff = Math.abs(num - closest); | |
currentDiff = Math.abs(num - ar[i]); | |
if(currentDiff < closestDiff) { | |
closest = ar[i]; | |
} | |
closestDiff = null; | |
currentDiff = null; | |
} | |
//returns first element that is closest to number | |
return closest; | |
} | |
//no length | |
return false; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment