Last active
March 10, 2016 03:36
-
-
Save nickleefly/91ffeb652bbb00d6339f to your computer and use it in GitHub Desktop.
get closest number from an array
This file contains 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
var counts = [4, 9, 15, 100, 2], | |
goal = 70; | |
function closest(array, x) { | |
var min, | |
chosen = array[0]; | |
for (var i in array) { | |
min = Math.abs(x - chosen); | |
if (Math.abs(x - array[i]) < min) { | |
chosen = array[i]; | |
} | |
} | |
return chosen; | |
} | |
console.log(closest(counts, goal)) |
This file contains 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
var counts = [4, 9, 15, 100, 2], | |
goal = 70; | |
// var closest = counts.reduce(function (prev, curr) { | |
// return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev; | |
// }); | |
var closest = counts.reduce((prev, curr) => | |
Math.abs(curr - goal) < Math.abs(prev - goal) ? | |
curr : prev | |
); | |
console.log(closest); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment