Group Date, Month with Javascript Reduce

var data = [{
  date: '2015-10-30',
  title: 'jerry'
}, {
  date: '2015-10-30',
  title: 'tom'
}, {
  date: '2015-10-31',
  title: 'tom'
}, {
  date: '2015-10-31',
  title: 'tom'
}, {
  date: '2015-11-01',
  title: 'tom'
}, {
  date: '2015-11-01',
  title: 'tom'
}, {
  date: '2015-11-02',
  title: 'tom'
}, {
  date: '2015-11-02',
  title: 'tom'
}, {
  date: '2015-11-03',
  title: 'tom'
}, {
  date: '2015-11-03',
  title: 'tom'
}];

var groupsLevel1 = _.reduce(data, groupByDate, {});
var groupsLevel2 = _.reduce(groupsLevel1, groupByMonth, {});

console.log(groupsLevel2);

function groupByDate(groups, item) {
  var date = item.date;
  var group;

  if (!(date in groups)) {
    group = groups[date] = [];
  } else {
    group = groups[date];
  }

  group.push(item);
  
  return groups;
}

function groupByMonth (groups, item) {
  var date = item[0].date,
      month = date.substr(0, 7),
      group;
  if (!(month in groups)) {
    group = groups[month] = {};
  } else {
    group = groups[month];
  }
  group[date] = item;
  return groups;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s