- ChatGPT is wild, asked for
function to find closest number given an array of numbers
and got :
/**
To find the closest number to a given number in an array of numbers, you can use a combination of the Math.abs() and Math.min() methods.
The Math.abs() method returns the absolute value of a number, which is the number without its sign (positive or negative). This is useful for comparing the distance between two numbers, because the distance between two numbers is always positive.
The Math.min() method returns the smallest number in a given array of numbers. This is useful for finding the smallest absolute difference between a given number and the numbers in an array.
Here is an example of a function that uses these methods to find the closest number to a given number in an array:
*/
function findClosestNumber(numbers, target) {
const distances = numbers.map(number => Math.abs(number - target));
const closestIndex = distances.indexOf(Math.min(...distances));
return numbers[closestIndex];
}
const numbers = [1, 5, 10, 15, 20];
const target = 12;
findClosestNumber(numbers, target)
// nearest will be 10