How to group objects with timestamps properties by day, week, month?

Viewed 49915

In a nodejs application, I have an array of event objects formatted as follows:

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

eventsArray having a variable length of n elements, and supposing I choose time reference to be Paris time, I want to be able to group elements by day, week, or month:

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: { ... }
                 }

Having very little experience with manipulating unix timestamps, I was wondering how this could be done or if there was an npm module that would make this easier.

6 Answers

Another implementation using dayjs library

var dayjs = require('dayjs')

function groupTimesBy(theList, unit = 'day', timeParamName = 'create_time'){
    var toReturn = {};

    for(let listItem of theList) {
        const paramName = dayjs.unix(listItem[timeParamName]).startOf(unit).unix();
        if(toReturn[paramName] == null) {
            toReturn[paramName] = [];
        }
        toReturn[paramName].push(listItem);
    }


    return toReturn;
}

let list = [{'time':1609104570}, {'time':1609104570}];

let byDay = groupTimesBy(list, 'day', 'time');
let byWeek = groupTimesBy(list, 'week', 'time');
let byMonth = groupTimesBy(list, 'month', 'time');
let byYear = groupTimesBy(list, 'year', 'time');
Related