Array Of JS Dates How To Group By Days

前端 未结 4 1470
旧时难觅i
旧时难觅i 2020-12-05 18:10

I\'m trying to figure out the most optimal and with as minimum amount of loops way to group my array of js dates objects from this: (Take a note this is browser console outp

4条回答
  •  长情又很酷
    2020-12-05 18:38

    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();
    

提交回复
热议问题