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

All the solutions above are hefty, pure JS, vanilla solutions. If you’re okay to use a couple of libraries, then lodash and moment can be used together for a simple one liner:

ES6

let groupedResults = _.groupBy(results, (result) => moment(result['Date'], 'DD/MM/YYYY').startOf('isoWeek'));

Older JS

var groupedResults = _.groupBy(results, function (result) {
  return moment(result['Date'], 'DD/MM/YYYY').startOf('isoWeek');
});

This will result in an array that’s keyed by the start of the week, such Mon Jul 25 2016 00:00:00 GMT+0100. I’m sure you can work out how to expand on it to get months, years, etc.

RE: @SaintScott’s comments

It was mentioned in the comments that this doesn’t directly answer the question because the original uses UTC timestamps rather than formatted dates. In this case, you should use moment() without the second parameter:

moment(1387271989749).startOf('isoWeek');

Or if using a UNIX timestamp, as follows:

moment.unix(yourTimestamp).startOf('isoWeek');

… although this is starting to get further from the question and more into the Moment documentation, which I’d advise reading if you want to use this method.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)