在 JavaScript 中找到数组中的最接近值


我们需要编写一个 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

更新于: 12-10-2020

179 次浏览

开启职业生涯

完成课程认证

开始
广告
© . All rights reserved.