Created
May 21, 2018 08:18
-
-
Save antfu/87d81996e43badbaaea2b999d1e6513d to your computer and use it in GitHub Desktop.
This file contains 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
function closest(num, arr) { | |
let idx = 0 | |
let curr = arr[idx] | |
let diff = Math.abs(num - curr); | |
for (var val = 0; val < arr.length; val++) { | |
var newdiff = Math.abs(num - arr[val]) | |
if (newdiff < diff) { | |
diff = newdiff | |
curr = arr[val] | |
idx = val | |
} | |
} | |
return { | |
value: curr, | |
index: idx | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment