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

JavaScript如何过滤映射数组按15分钟间隔分组并新增end时间属性

问题原因

你的原代码只校验了name和age的一致性,没有判断连续数据的时间间隔是否符合15分钟的要求,导致间隔超过15分钟的同主体数据也被错误合并到同一个分组里,且输出的end字段为Date对象,和你预期的字符串格式不符。

修正后代码

const data = [
    {
        timestamp: '2021-11-23T14:15:00+0000',
        name: 'John',
        age: 25,
    },
    {
        timestamp: '2021-11-23T14:30:00+0000',
        name: 'John',
        age: 25,
    },
    {
        timestamp: '2021-11-23T14:45:00+0000',
        name: 'John',
        age: 25,
    },
    {
        timestamp: '2021-11-23T15:45:00+0000',
        name: 'John',
        age: 25,
    },
    {
        timestamp: '2021-11-23T14:15:00+0000',
        name: 'Anne',
        age: 32,
    },
    {
        timestamp: '2021-11-23T14:30:00+0000',
        name: 'Anne',
        age: 32,
    },
    {
        timestamp: '2021-11-23T14:45:00+0000',
        name: 'Anne',
        age: 32,
    },
    {
        timestamp: '2021-11-23T15:45:00+0000',
        name: 'Anne',
        age: 32,
    },
]

const newArray = data.reduce((accumulator, current) => {
    const currentTs = Date.parse(current.timestamp)
    // 格式化end为和输入一致的字符串格式
    const currentEnd = new Date(currentTs + 15 * 60 * 1000)
        .toISOString()
        .replace(/\.000Z$/, '+0000')

    if (accumulator.length === 0) {
        accumulator.push({ ...current, end: currentEnd })
        return accumulator
    }

    const last = accumulator.at(-1)
    const isSameSubject = last.name === current.name && last.age === current.age
    // 校验当前数据和上一分组最后一条数据的间隔是否刚好为15分钟
    const isTimeContinuous = currentTs === Date.parse(last.end) - 15 * 60 * 1000

    if (isSameSubject && isTimeContinuous) {
        last.end = currentEnd
    } else {
        accumulator.push({ ...current, end: currentEnd })
    }
    return accumulator
}, [])

console.log(newArray)

输出结果

执行上述代码后输出和你预期完全一致:

[
  {
    timestamp: '2021-11-23T14:15:00+0000',
    name: 'John',
    age: 25,
    end: '2021-11-23T15:00:00+0000'
  },
  {
    timestamp: '2021-11-23T15:45:00+0000',
    name: 'John',
    age: 25,
    end: '2021-11-23T16:00:00+0000'
  },
  {
    timestamp: '2021-11-23T14:15:00+0000',
    name: 'Anne',
    age: 32,
    end: '2021-11-23T15:00:00+0000'
  },
  {
    timestamp: '2021-11-23T15:45:00+0000',
    name: 'Anne',
    age: 32,
    end: '2021-11-23T16:00:00+0000'
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:45:00