Skip to content

Instantly share code, notes, and snippets.

@jswhisperer
Created May 9, 2013 10:34
Show Gist options
  • Save jswhisperer/5546782 to your computer and use it in GitHub Desktop.
Save jswhisperer/5546782 to your computer and use it in GitHub Desktop.
Pass an array and a value, get back the closest number.
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