You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中优雅查找Set中大于指定值的最小数的方法

一行代码实现查找Set中大于初始值的最小数值

针对你的需求,可以结合数组方法和展开运算符实现一行代码解决方案:

const smallestGreater = Math.min(...Array.from(mySet).filter(num => num > initVal)) || Infinity;

代码解析

  • Array.from(mySet):将Set集合转换为数组,以便使用数组的过滤和聚合方法
  • .filter(num => num > initVal):筛选出所有大于初始值initVal的元素
  • ...展开运算符:把筛选后的数组元素逐个传入Math.min(),获取其中的最小值
  • || Infinity:当没有符合条件的元素时,Math.min()会返回Infinity,这里保持和你原代码的逻辑一致(原代码初始值设为Infinity)

用你提供的示例测试:

const mySet = new Set([1, 4, 5])
const initVal = 2
const smallestGreater = Math.min(...Array.from(mySet).filter(num => num > initVal)) || Infinity;
console.log(smallestGreater) // 输出 4

如果需要更紧凑的写法,也可以利用Array.from的第二个参数直接处理筛选,不过可读性稍弱:

const smallestGreater = Math.min(...Array.from(mySet, num => num > initVal ? num : Infinity));

内容的提问来源于stack exchange,提问作者esafresa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 07:05:32