Skip to content

Instantly share code, notes, and snippets.

@antfu
Created May 21, 2018 08:18
Show Gist options
  • Save antfu/87d81996e43badbaaea2b999d1e6513d to your computer and use it in GitHub Desktop.
Save antfu/87d81996e43badbaaea2b999d1e6513d to your computer and use it in GitHub Desktop.
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