-1

I am trying to get an array of all days in a week like today is Aug 1st so i need to get an array of this week which will look like

['2019-07-28' ,'2019-07-29', '2019-07-30', '2019-07-31', '2019-08-01', '2019-08-02', '2019-08-03']

in order to achieve this i wrote the following code

var week_list = []
const today = new Date()
week_list.push(today.toISOString().substring(0,10))
var counter = today.getDay()
// get next 
var next_day = today
for(var i = counter;i<6;i++){
    next_day.setDate(next_day.getDate()+1)
    week_list.push(next_day.toISOString().substring(0,10))
}
// get prev 
var prev_day = today
for(var i = counter;i>0;i--){
    prev_day.setDate(prev_day.getDate()-1)
    week_list.push(prev_day.toISOString().substring(0,10))
}   

console.log(week_list)

output

[ '2019-08-01', '2019-08-02', '2019-08-03', '2019-08-02', '2019-08-01', '2019-07-31', '2019-07-30']

i am getting a different output instead of what i was expecting, the variable today change automatically when i try to update the next_day variable. Is this common under javascript else am i doing anything wrong.

skid
  • 958
  • 4
  • 13
  • 29
  • 1
    @JstnPwll's answer is correct: `next_day`, `today`, and `prev_day` all point to the same underlying object; by changing one, you are also changing the others. – RWRkeSBZ Aug 01 '19 at 16:18
  • I'd also like to point out that none of the codes here, either your own or the answers are going to give the exact output you asked for. – Anurag Srivastava Aug 01 '19 at 16:19
  • when i follow the @JstnPwl's instruction i am getting the output which i was expecting – skid Aug 01 '19 at 16:22

2 Answers2

3

next_day is a reference to the same object that today references. The underlying date object is the same. If you want two different objects, you should construct a new date.

var next_day = new Date()
...
var prev_day = new Date()
JstnPwll
  • 8,585
  • 2
  • 33
  • 56
0

const dates = (current) => {
    const week = []; 
    current.setDate((current.getDate() - current.getDay() +1));
    for (var i = 0; i < 7; i++) {
        week.push(
            new Date(current).toISOString().substring(0,10)
        ); 
        current.setDate(current.getDate() +1);
    }
    return week; 
}
console.log(dates(new Date()));
Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26