Last active
February 5, 2016 21:45
-
-
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.
This file contains hidden or 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
/* | |
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