【问题标题】:How to group data into arrays by intervals如何按间隔将数据分组到数组中
【发布时间】:2021-09-10 04:29:36
【问题描述】:

所以我有一个大型数据数组,其中的对象如下所示:

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
  }
}

使用下面的代码,我设法使用 lodash groupBy 函数和 momentjs 按天对所有数据进行分组,这正是我想要的,它存储在一个数组数组中,每个数组都有所有带有时间戳的对象(称为 localcol)有同一天。

queryAllPartitions().then((rowResults) => {
    console.log('Final Row Length', rowResults.length);

    let byDay = _.groupBy(rowResults, (result) => moment(result['localcol'], 'DD/MM/YYYY').startOf('day'));

    const groupInterval = 900000 // 15 min
    let byTimePeriod = [];

    const result = []
    for (let i = 0; i < Object.entries(byDay).length; i++) { // 30
        console.log("day", i)

        byTimePeriod[i] = []
        byTimePeriod[i] = _.groupBy((Object.entries(byDay)[i][1]), (result) => moment(result['localcol'], 'DD/MM/YYYY').startOf('minute'));
    }
}

我的问题是我必须像这样在某个时间再次对它们进行分组:

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

我可以使用 lodash 和 momentjs 将它们按分钟和小时分组:

byTimePeriod[i] = _.groupBy((Object.entries(byDay)[i][1]), (result) => moment(result['localcol'], 'DD/MM/YYYY').startOf('minute'));

byTimePeriod[i] = _.groupBy((Object.entries(byDay)[i][1]), (result) => moment(result['localcol'], 'DD/MM/YYYY').startOf('hour'));

但我不知道如何为其他 2 分钟(5 分钟和 15 分钟)做这件事。 我查看了 momentjs 上的文档:https://momentjscom.readthedocs.io/en/latest/moment/03-manipulating/03-start-of/,但在尝试了很长时间后,我认为使用 startof 可能无法实现,我必须使用不同的方法对它们进行分组。

【问题讨论】:

    标签: javascript node.js timestamp momentjs lodash


    【解决方案1】:

    基本上startOf 函数将指定的日期字段设置为零。

    要按 5 分钟分组,您必须获取当前分钟数并检查它们是否在正确的时间间隔内,为此您需要获取当前分钟数 / 5 * 5。

    将 5 替换为 15 持续 15 分钟。

    显然这项工作从0开始间隔:

    • 0-4 = 0
    • 5-9 = 5

    等等

    (result) => moment(result['localcol'], 'DD/MM/YYYY').minutes(Math.floor(moment(result['localcol'], 'DD/MM/YYYY').minutes() / 5) * 5);;
    moment(date, 'DD/MM/YYYY').minutes(minutes);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      相关资源
      最近更新 更多