Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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