숫자 배열을 첫 번째 인수로, 숫자를 두 번째 인수로 취하는 JavaScript 함수를 작성해야 합니다. 그런 다음 함수는 두 번째 인수로 함수에 제공된 숫자에 가장 가까운 배열에서 숫자를 반환해야 합니다.
예시
이에 대한 코드는 -
const arr = [3, 56, 56, 23, 7, 76, -2, 345, 45, 76, 3];
const num = 37
const findClosest = (arr, num) => {
const creds = arr.reduce((acc, val, ind) => {
let { diff, index } = acc;
const difference = Math.abs(val - num);
if(difference < diff){
diff = difference;
index = ind;
};
return { diff, index };
}, {
diff: Infinity,
index: -1
});
return arr[creds.index];
};
console.log(findClosest(arr, num)); 출력
콘솔의 출력 -
45