Skip to content

Instantly share code, notes, and snippets.

@phellipeandrade
Created September 13, 2017 16:59
Show Gist options
  • Save phellipeandrade/e489eeb4295251f240487fa3cf6f70d0 to your computer and use it in GitHub Desktop.
Save phellipeandrade/e489eeb4295251f240487fa3cf6f70d0 to your computer and use it in GitHub Desktop.
// 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