Skip to content

Instantly share code, notes, and snippets.

@atesgoral
Created April 24, 2014 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atesgoral/11261918 to your computer and use it in GitHub Desktop.
Save atesgoral/11261918 to your computer and use it in GitHub Desktop.
Find the closest match in an array of numbers
function findClosestToDesired(values, desired) {
return values
.slice(0)
.sort(function (a, b) {
return Math.abs(desired - a) - Math.abs(desired - b);
})
.shift();
}
// findClosestToDesired([ 1, 3, 7, 15 ], 6) === 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment