Skip to main content

The closest number in an array

Find the closest number in an array of numbers

Write your solution:
Test Case 1
Input: [4,9,15,6,2], 5
Output: 4
Test Case 2
Input: [-5,3,12,45,-99], 13
Output: 12
Test Case 3
Input: [-1.5,0.5,1.46,1.51,1.69], 1.5
Output: 1.51
Solution
function findClosest(nums, target) {
return nums.reduce((prev, curr) => (Math.abs(curr - target) < Math.abs(prev - target) ? curr : prev));
}