【问题标题】:Nodejs - Group large array objects by their timestamp propertyNodejs - 按时间戳属性对大型数组对象进行分组
【发布时间】:2021-06-24 23:06:42
【问题描述】:

我有一个包含大量对象的数组(大约 200k 到 1M 个条目)。每个对象如下所示:

Row {
  month_year_index: 'september_2019_2',
  localcol: 2019-09-13T00:52:16.847Z,
  datamap: {
    Curr1_mA: 769,
    Curr2_mA: 139,
    Curr3_mA: 0,
    P1_W: 75,
    P2_W: 0,
    P3_W: 0,
    P_Total_W: 75,
    U1N_Vx10: 2261,
    U2N_Vx10: 2330,
    U3N_Vx10: 2360
  }
}

我每 10 秒就有一次这些对象,我需要将它们按一个 timeUnit 分组,如下所示:

  • 1 分钟 = 60000 毫秒
  • 5 分钟 = 300000 毫秒
  • 15 分钟 = 900000 毫秒
  • 1 小时 = 3600000 毫秒

所以,基本上我需要将原始数组转换为一个数组数组,其中该数组的第一个元素将是一个包含此范围内对象的数组(在示例中使用 5 分钟作为时间单位):

[[first_object_timestamp, first_object_timestamp + 300000], [first_object_timestamp + 30000,first_object_timestamp + 600000]]

如果更简单,您可以将数组转换为单个对象,其中 datamap 属性具有值的平均值,因为无论如何我都必须这样做。

【问题讨论】:

    标签: javascript node.js arrays timestamp grouping


    【解决方案1】:

    有几件事会使您的场景变得复杂:

    • 日期为 localcol 属性的对象
    • 日期需要解析成数字格式

    为简单起见,我的回答假设以下几点:

    • 这只是一个数字数组。不是对象数组。您可以修改此示例以适合您的场景。
    • 时间按升序排列

    const groupInterval = 5
    const times = [2, 3, 4, 5, 8, 14, 15, 18, 53, 402, 403]
    
    const result = []
    for (let i = 0; i < times.length;) {
      // Get starting time of group
      const firstTimeInGroup = Math.floor(times[i] / groupInterval) * groupInterval
      const group = []
      for (; times[i] < firstTimeInGroup + groupInterval; i++) {
        group.push(times[i])
      }
      result.push(group)
    }
    console.log(result)

    【讨论】:

    • 嘿,感谢您的帮助,我怎样才能使间隔为固定值:例如 5 分钟:[00:00:00, 00:05:00], [00:05: 00, 00:10:00], [00:10:00, 00:15:00] 等
    • 我将 sn-p 更新为具有固定的间隔值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2021-11-25
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    相关资源
    最近更新 更多