Created
September 13, 2017 16:59
-
-
Save phellipeandrade/e489eeb4295251f240487fa3cf6f70d0 to your computer and use it in GitHub Desktop.
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
// Based on: https://stackoverflow.com/questions/8584902/get-closest-number-out-of-array | |
const arr = [360, 375, 414, 768, 1024]; | |
// ES6 | |
const closest = (num, arr) => { | |
let curr = arr[0]; | |
let diff = Math.abs(num - curr); | |
for (let i of arr) { | |
const newDiff = Math.abs(num - i); | |
if (newDiff < diff) { | |
diff = newDiff; | |
curr = i | |
} | |
} | |
return curr; | |
} | |
//ES5 | |
function closest(num, arr) { | |
var curr = arr[0]; | |
var diff = Math.abs(num - curr); | |
for (var val = 0; val < arr.length; val++) { | |
var newDiff = Math.abs(num - arr[val]); | |
if (newDiff < diff) { | |
diff = newDiff; | |
curr = arr[val]; | |
} | |
} | |
return curr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment