Forked from vipickering/closestNumberArray.js
Last active
September 13, 2016 14:38
-
-
Save joonassandell/58d123ca7916ec8072d8 to your computer and use it in GitHub Desktop.
Find closest number in ES6
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
const closestNumber = (array, num) => { | |
const i = 0; | |
let minDiff = 1000; | |
let ans; | |
for (i in array){ | |
const m = Math.abs(num - array[i]); | |
if (m < minDiff) { | |
minDiff = m; | |
ans = array[i]; | |
} | |
} | |
return ans; | |
} | |
/** | |
* Call array name and desired value to be closest | |
*/ | |
const array = ['100', '50']; | |
console.log(closestNumber(array, 88)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment