如何从一组特定数字中找到最接近的较大数字:JavaScript?

javascriptweb developmentfront end technologyobject oriented programming

我们有一组数字,我们的要求是找到与作为函数输入的特定数字相同或最接近的较大数字键。

数字集定义为 −

const numbers = {
   A:107,
   B:112,
   C:117,
   D:127,
   E:132,
   F:140,
   G:117,
   H:127,
   I:132,
   J:132,
   K:140,
   L:147,
   M:117,
   N:127,
   O:132
};

示例

其代码为 −

const numbers = {
   A:107,
   B:112,
   C:117,
   D:127,
   E:132,
   F:140,
   G:117,
   H:127,
   I:132,
   J:132,
   K:140,
   L:147,
   M:117,
   N:127,
   O:132
};
const nearestHighest = (obj, val) => {
   let diff = Infinity;
   const nearest = Object.keys(obj).reduce((acc, key) => {
      let difference = obj[key] - val;
      if (difference >= 0 && difference < diff) {
         diff = difference;
         acc = [key];
      }
      return acc;
   }, [])
   return nearest;
};
console.log(nearestHighest(numbers, 140));

输出

控制台中的输出将是 −

['F']

相关文章