JavaScript如何按阈值过滤数组并合并连续时间元素为起止对象
JavaScript 数组处理实现方案
核心逻辑拆分
- 第一步:过滤出
amount大于等于阈值的元素 - 第二步:对过滤后的元素按「相邻元素timestamp间隔为10分钟」的规则分组
- 第三步:将每个分组转换为要求的
start/end格式,end统一取分组最后一个元素的timestamp加10分钟
原有代码的问题在于没有做连续分组逻辑,且用slice截取小时判断的方式兼容性差,跨小时的相邻10分钟场景会判断错误,也没有正确处理时间加10分钟的逻辑。
完整实现代码
const data = [{ timestamp: '2021-11-23T14:00:00+0000', amount: 21 }, { timestamp: '2021-11-23T14:10:00+0000', amount: 27 }, { timestamp: '2021-11-23T14:20:00+0000', amount: 31 }, { timestamp: '2021-11-23T14:30:00+0000', amount: 29 }, { timestamp: '2021-11-23T14:40:00+0000', amount: 18 }, { timestamp: '2021-11-23T14:50:00+0000', amount: 17 }, { timestamp: '2021-11-23T15:00:00+0000', amount: 25 }, { timestamp: '2021-11-23T15:10:00+0000', amount: 21 } ] // 常量定义,10分钟对应的毫秒数 const TEN_MINUTES = 10 * 60 * 1000 const threshold = 25 // 第一步:过滤符合阈值的元素 const aboveThreshold = data.filter(item => item.amount >= threshold) // 第二步:按间隔规则分组 const groups = aboveThreshold.reduce((acc, current) => { const lastGroup = acc[acc.length - 1] // 初始化第一个分组 if (!lastGroup) return [[current]] const lastItem = lastGroup[lastGroup.length - 1] const timeDiff = new Date(current.timestamp).getTime() - new Date(lastItem.timestamp).getTime() if (timeDiff === TEN_MINUTES) { // 间隔符合要求,归入当前分组 lastGroup.push(current) } else { // 间隔不符合,新建分组 acc.push([current]) } return acc }, []) // 第三步:转换为要求的输出格式 const workSchedule = groups.map(group => { const start = group[0].timestamp const endTimestamp = new Date(group[group.length - 1].timestamp).getTime() + TEN_MINUTES // 转换回原时间格式,适配UTC+0000的格式要求 const end = new Date(endTimestamp).toISOString().replace('.000Z', '+0000') return { start, end } }) console.log(workSchedule)
方案优势
逻辑拆分清晰,每一步职责单一,可读性和可维护性强。用时间戳计算差值的方式兼容性强,跨小时、跨天的相邻场景都能正确判断,后续调整阈值、间隔时长等规则时只需修改对应常量即可。
内容的提问来源于stack exchange,提问作者user13695382
相关产品推荐
相关产品推荐

