Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nguyenbathanh/5497260d9feb6c34ad4981bba5d42455 to your computer and use it in GitHub Desktop.
Save nguyenbathanh/5497260d9feb6c34ad4981bba5d42455 to your computer and use it in GitHub Desktop.
var test = 24,
arr = [76,56,22,89,74].sort(); // just sort it generally if not sure about input, not really time consuming
function getClosest(test, arr) {
var num = 0, result = 0;
var flag = 0;
for(var i = 0; i < arr.length; i++) {
num = arr[i];
if(num < test) {
result = num;
flag = 1;
}else if (num == test) {
result = num;
break;
}else if (flag == 1) {
if ((num - test) < (Math.abs(arr[i-1] - test))){
result = num;
}
break;
}else{
break;
}
}
return result;
}
console.log(getClosest(test, arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment