Created
July 15, 2016 03:52
-
-
Save nguyenbathanh/5497260d9feb6c34ad4981bba5d42455 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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