一尘不染

如何按天,周,月将带有时间戳属性的对象分组?

node.js

在nodejs应用程序中,我有一组事件对象,其格式如下:

eventsArray = [ {id: 1, date: 1387271989749 }, {id:2, date: 1387271989760}, ... ]

eventsArray具有n个元素的可变长度,并且假设我选择时间参考为巴黎时间,我希望能够按天,周或月对元素进行分组:

groupedByDay = {

            2012: { ... },
            2013: {
              dayN  : [{id: a0, date: b0}, {id: a1, date: b1}, {id: a2, date: b2 }],
              dayN+1: [{id: a3, date: b3}, {id: a4, date: b4}, {id: a5, date: b5 }],
              ...
                   },
            2014: { ... }

          }

groupedByWeek = {
            2012: { ... }
            2013: {
              weekN: [{id: a0, date: b0}, {id: a1, date: b1}, {id: a2, date: b2 }],
              weekN+1: [{id: a3, date: b3}],
              ....
                  },
             2014: { ... }
                }

groupedByMonth = {
             2012: { ... },
             2013: {
               monthN: [ {id: a0, date: b0 }, {id: a1, b1}, {id: a2, b2}, {id: a3, b3 }],
               monthN+1: [ {id: a4, date: b4 }, {id: a5, b5}, {id: a6, b6}],
               ...
                   },
              2014: { ... }
                 }

我对操纵unix时间戳经验很少,我想知道如何做到这一点,或者是否有npm模块可以简化此过程。


阅读 211

收藏
2020-07-07

共1个答案

一尘不染

这是我的解决方案。请记住,从纪元开始,天,周和月相对于原点:

eventsArray = [ {id: 1, date: 1387271989749 }, {id:2, date: 1387271989760} ];
byday={};
byweek={};
bymonth={};
function groupday(value, index, array)
{
    d = new Date(value['date']);
    d = Math.floor(d.getTime()/(1000*60*60*24));
    byday[d]=byday[d]||[];
    byday[d].push(value);
}
function groupweek(value, index, array)
{
    d = new Date(value['date']);
    d = Math.floor(d.getTime()/(1000*60*60*24*7));
    byweek[d]=byweek[d]||[];
    byweek[d].push(value);
}
function groupmonth(value, index, array)
{
    d = new Date(value['date']);
    d = (d.getFullYear()-1970)*12 + d.getMonth();
    bymonth[d]=bymonth[d]||[];
    bymonth[d].push(value);
}
eventsArray.map(groupday);
eventsArray.map(groupweek);
eventsArray.map(groupmonth);
2020-07-07