Skip to content

Instantly share code, notes, and snippets.

@Lewiscowles1986
Forked from vipickering/closestNumberArray.js
Created August 26, 2018 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lewiscowles1986/a4814971f873a08ed0cb2c90f411d476 to your computer and use it in GitHub Desktop.
Save Lewiscowles1986/a4814971f873a08ed0cb2c90f411d476 to your computer and use it in GitHub Desktop.
Javascript: Find The Closest Number In Array To A Specific Value
var array = [];
function closest(array,num){
var i=0;
var minDiff=1000;
var ans;
for(i in array){
var m=Math.abs(num-array[i]);
if(m<minDiff){
minDiff=m;
ans=array[i];
}
}
return ans;
}
/*call array name and desired value to be closet */
alert(closest(array,88));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment