A. Nurb
A. Nurb

Reputation: 536

Angular template: grouping rows on month

I have the following objects:

{
    "pk": 33,
    "name": "EVENT 634",
    "start_date": "2022-05-11T00:00:00",
    "end_date": "2022-05-14T00:00:00"
},
{
    "pk": 32,
    "name": "Event AAB",
    "start_date": "2022-06-02T00:00:00",
    "end_date": "2022-06-04T00:00:00"
},
{
    "pk": 26,
    "name": "Event LKS",
    "start_date": "2022-06-02T00:00:00",
    "end_date": "2022-06-12T00:00:00"
}

And I have a template:

<div *ngFor="let event of events">
    <div class="month-row">{{ event.start_date | date: 'MMMMYY'}}
    </div>
    <div class="name">{{ event.name }}</div>
</div>

The template gives me

June 2021
Event nameX
June 2021
Event nameY
June 2021
Event nameZ

but I would like to have

June 2021
Event nameX
Event nameY
Event nameZ
July 2021
Event nameA
Event nameB
Event nameC

In other words: I would like to group the events per month OR hide the monthname if it was already shown.

Any ideas?

Upvotes: 0

Views: 67

Answers (1)

Yong Shun
Yong Shun

Reputation: 51240

To group by month and year:

  1. Use .reduce(). Returns dictionary with key as Date string and an object with date property and events array.
  2. Transform dictionary to the array.
let monthGroup = this.events.reduce(function (r, o) {
  let year = o.start_date.split('-')[0];
  let month = o.start_date.split('-')[1];

  let groupedDate = new Date(year, month, 1);
  let groupedDateString = `${groupedDate.getFullYear()}-${groupedDate.getMonth()}-${groupedDate.getDate()}`;

  r[groupedDateString]
    ? r[groupedDateString].events.push(o)
    : (r[groupedDateString] = { date: groupedDate, events: [o] });
  return r;
}, {});

this.eventsByMonth = Object.keys(monthGroup).map(function (k) {
  return monthGroup[k];
});

console.log(this.eventsByMonth);
<div *ngFor="let month of eventsByMonth">
  <div class="month-row">{{ month.date | date: 'MMMM YY' }}</div>
  <div *ngFor="let event of month.events">
    <div class="name">{{ event.name }}</div>
  </div>
  <hr />
</div>

Output

enter image description here

Sample Solution on StackBlitz

Upvotes: 2

Related Questions