Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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));
@taqiabdulaziz

This comment has been minimized.

Copy link

taqiabdulaziz commented Sep 28, 2018

Thanks.

@robbywashere

This comment has been minimized.

Copy link

robbywashere commented Sep 28, 2018

I came up with this ...
const nearest = (arr) => val => arr.reduce((p,n) => Math.abs(p) > Math.abs(n-val) ? n-val : p, Infinity) + val;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.