Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Elements in the date array update automatically

I’m trying to find week days between first date and second date (exclusive first and second). In the array that contains the weekday dates, the values get increment after line 1 in executed, which is unexpected.

private getListOfWeekDaysBetweenTwoDates(
    startDate: Date,
    endDate: Date
  ): Date[] {
    const weekdaysList = [];
    let tempDate = this.addDaystoGivenDate(startDate, 1);
    while (tempDate < endDate) {
      if (this.isWeekDay(tempDate)) {
        weekdaysList.push(tempDate);
      }
//line 1
      tempDate = this.addDaystoGivenDate(tempDate, 1);
    }
    return weekdaysList;
  }

 private addDaystoGivenDate(date: Date, numberOfDays: number): Date {
    return new Date(date.setUTCDate(date.getUTCDate() + numberOfDays));
  }

private isWeekDay(day: Date): boolean {
    if (day.getUTCDay() >= 1 && day.getUTCDay() <= 5) {
      return true;
    }
    return false;
  }

How do I stop array values changing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Isolating the problem, you’re changing the date after inserting it to the array, but what you’re inserting is a reference to the date:

let d = new Date()
d.setUTCDate(1)
const arr = []
arr.push(d)
console.log(arr)
d.setUTCDate(10)
console.log(arr) //date in arr changes from 1 to 10

That’s because you’re calling date.setUTCDate() over tempDate.

There is more than one way to solve it, but for example you could store not the reference to tempDate but a completely new Date object:

weekdaysList.push(tempDate); => weekdaysList.push(new Date(tempDate));

In the simplified example:

let d = new Date()
const arr = []
d.setUTCDate(1)
arr.push(new Date(d))
console.log(arr)
d.setUTCDate(10)
console.log(arr) //date in arr keeps 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading