This function finds the number in an array that is closest to a given target number.
JavaScript:
let closestNum = (arr, target) => arr.reduce((prev, curr) => Math.abs(curr - target) < Math.abs(prev - target) ? curr : prev);
// Example
console.log(closestNum([10, 22, 28, 29, 30, 40], 54)); // 40
console.log(closestNum([2, 5, 6, 7, 8, 8], 4)); // 5
TypeScript:
let closestNum = (arr: number[], target: number): number => arr.reduce((prev, curr) => Math.abs(curr - target) < Math.abs(prev - target) ? curr : prev);
// Example
console.log(closestNum([10, 22, 28, 29, 30, 40], 54)); // 40
console.log(closestNum([2, 5, 6, 7, 8, 8], 4)); // 5