且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JS日期数组如何按天分组

更新时间:2022-05-04 22:30:29

Underscore有 _。groupBy 功能应该完全符合您的要求:

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.

要将对象转换为与问题中相同形式的数组,您可以使用map:

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