Array Of JS Dates How To Group By Days

Underscore has the _.groupBy function which should do exactly what you want:

var groups = _.groupBy(occurences, function (date) {
  return moment(date).startOf('day').format();
});

This will return an object where each key is a day and the value an array containing all the occurrences for that day.

To transform the object into an array of the same form as in the question you could use map:

var result = _.map(groups, function(group, day){
    return {
        day: day,
        times: group
    }
});

To group, map and sort you could do something like:

var occurrenceDay = function(occurrence){
    return moment(occurrence).startOf('day').format();
};

var groupToDay = function(group, day){
    return {
        day: day,
        times: group
    }
};

var result = _.chain(occurences)
    .groupBy(occurrenceDay)
    .map(groupToDay)
    .sortBy('day')
    .value();

Leave a Comment