Skip to content

Instantly share code, notes, and snippets.

@bignimbus
Last active February 5, 2016 21:45
Show Gist options
  • Save bignimbus/dc0823f19fe6d49c2614 to your computer and use it in GitHub Desktop.
Save bignimbus/dc0823f19fe6d49c2614 to your computer and use it in GitHub Desktop.
Given a number and an array of numbers, return the number in an array that is closest to that number.
/*
closest(0.5, [0, 1, 2, 3]); // 1
closest(0.4, [0, 1, 2, 3]); // 0
*/
function closest (num, arr) {
if (!arr || !arr.length) {
return;
}
return arr.slice(0).sort(function (a, b) {
var diffA = Math.abs(a - num),
diffB = Math.abs(b - num);
if (diffA < diffB) {
return -1;
} else if (diffA === diffB) {
return a > b ? -1 : 1;
}
return 1;
})[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment