Introduction
In this lab, we will explore how to find the closest number from an array using JavaScript. We will use the Array.prototype.reduce() method and the Math.abs() function to compare the distance between each element in the array and a target value, returning the closest match. By the end of this lab, you will have a better understanding of how to implement this useful function in your JavaScript projects.
A Function to Find the Closest Numeric Match in an Array
To find the closest number in an array, use the following function:
const closest = (arr, n) =>
arr.reduce((acc, num) => (Math.abs(num - n) < Math.abs(acc - n) ? num : acc));
Here's how to use it:
- Open the Terminal/SSH.
- Type
node. - Use the
closest()function and provide the array and the target value as arguments.
Example usage: closest([6, 1, 3, 7, 9], 5) will return 6, which is the closest number to 5 in the array.
Summary
Congratulations! You have completed the Closest Numeric Match lab. You can practice more labs in LabEx to improve your skills.