Skip to content

Instantly share code, notes, and snippets.

@gregpalaci
Created May 9, 2013 10:34
Show Gist options
  • Save gregpalaci/5546782 to your computer and use it in GitHub Desktop.
Save gregpalaci/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