DValdir Martins
DValdir Martins

Reputation: 181

Array Group By Month and Day

Let's say I have an array of People:

{ objectId: string; name: string; birth: Date;}

How would I split this array, grouping people that have the same month and then the same day of birth? I could filter by month:

    MONTHS.forEach((month) => {
      if (results) {
        const monthFilter = results.filter(x => x.birth.getMonth() +1 === month.number)
          console.log(month.month, monthFilter);
      }
    });

But I don't know how could I filter and group the ones who have birth in the same month and day.

Obs.: Year is irrelevant in this context.

EDIT

I got it working as follows:

  treatMonths(results: Member[]) {
    MONTHS.forEach((month) => {
      const monthSize = this.GetDaysInMonth(month.number);
      console.log(month.month, monthSize);
      
      const bMonth: BirthMonth = new BirthMonth();
      bMonth.monthName = month.month;
      bMonth.monthNumber = month.number;
      bMonth.days = [];

      for (let day = 1; day <= monthSize; ++day) {
        const dayOfMonth: DayOfMonth = new DayOfMonth();
        dayOfMonth.day = day;
        dayOfMonth.members = [];
        dayOfMonth.members = results.filter(x => (x.birth.getMonth() +1 === month.number) && (x.birth.getDate() === day));
        if (dayOfMonth.members.length) {
          bMonth.days.push(dayOfMonth);
        }
      }
      if (bMonth.days.length) {
        if (!this.birthMembers.find(x => x.monthNumber === month.number)) {
          this.birthMembers.push(bMonth);
        }
      }
    });
    this.birthMembersSubject.next(this.birthMembers);
  }

  GetDaysInMonth(month: number) {
    var date = new Date();
    if (month === 2) {
      return 29;
    } else {
      return new Date(date.getFullYear(), month, 0).getDate();
    }
  }

Don't know if it's the best approach, but for now, it's returning the way I need.

Upvotes: 0

Views: 661

Answers (1)

er-sho
er-sho

Reputation: 9771

If you could add day filter in your array.filter then it might be return the result that you want like

const monthFilter = results.filter(x => (x.birth.getMonth() +1 === month.number) && (x.birth.getDay() === month.day))

Upvotes: 1

Related Questions