We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a single number as the second argument.
The function should find and return that number from the array which is closest to the number specified by the second argument.
For example −
const arr = [34, 67, 31, 53, 89, 12, 4]; const num = 41;
Then the output should be 34.
Example
Following is the code −
const arr = [34, 67, 31, 53, 89, 12, 4];
const num = 41;
const findClosest = (arr = [], num) => {
let curr = arr[0];
let diff = Math.abs (num - curr);
for (let val = 0; val < arr.length; val++) {
let newdiff = Math.abs (num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
};
};
return curr;
};
console.log(findClosest(arr, num));Output
Following is the output on console −
34