Skip to content

Instantly share code, notes, and snippets.

@jquery404
Created October 26, 2018 04:08
Show Gist options
  • Save jquery404/09264edfab0fdb544f608444ba1c1f5f to your computer and use it in GitHub Desktop.
Save jquery404/09264edfab0fdb544f608444ba1c1f5f to your computer and use it in GitHub Desktop.
var goal = 25;
var numbers = [21, 34, 12, 52, 43];
var closest = numbers.reduce(function(prev, cur){
return (Math.abs(cur-goal) < Math.abs(prev-goal)) ? cur : prev;
});
console.log(closest); // output: 21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment