Find the closest number from an array

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
Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *