Why is my array being overwritten? - javascript

I am using node.js for a project and I am trying to add certain dates to an array. However, when I do, it overwrites the entire array with the current date being added. Source below:
let startDate = new Date(2014, 0, 8, 19, 0, 0)
let endDate = new Date(2014, 0, 11, 19, 0, 0)
let datesToDownload = []
let datesInDB = [new Date(2014, 0, 8, 19, 0, 0), new Date(2014, 0, 9, 19, 0, 0), new Date(2014, 0, 10, 19, 0, 0), new Date(2014, 0, 8, 11, 0, 0)]
for (let i = startDate; i <= endDate; i.setDate(i.getDate() + 1)) {
console.log('CHECKING DATE: ' + i.toDateString())
if (!(datesInDB2.indexOf(i.toDateString()) >= 0)) {
console.log('NEW RECORD FOUND FOR: ' + i.toDateString())
datesToDownload.push(i)
console.log('i: ' + i)
for (let j in datesToDownload) {
console.log('element ' + j + ': ' + datesToDownload[j])
}
}
}
And the output looks like this:
CHECKING DATE: Wed Jan 08 2014
NEW RECORD FOUND FOR: Wed Jan 03 2014
i: Wed Jan 08 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 0: Wed Jan 08 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
CHECKING DATE: Thur Jan 09 2016
NEW RECORD FOUND FOR: Thur Jan 09 2016
i: Thur Jan 09 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 0: Thur Jan 09 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 1: Thur Jan 09 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
CHECKING DATE: Fri Jan 10 2016
NEW RECORD FOUND FOR: Fri Jan 10 2016
i: Fri Jan 10 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 0: Fri Jan 10 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 1: Fri Jan 10 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 2: Fri Jan 10 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
......
Notice how the elements are all changed to the current date being inserted, though an element is being added.
Why is this happening? How can I prevent it?

You're pushing exactly the same Date instance into the array on each iteration. You can create a copy of it however:
datesToDownload.push(new Date(i));

A date is an object, and is passed by reference. In your for loop you are changing the date:
for (let i = startDate; i <= endDate; i.setDate(i.getDate() + 1)) {

Related

How to increase the date when moving to the other month

I have a date set which I am filling it with the number of current week and year:
dateSets(week, year) {
let fistDayOfTheWeek = '';
if(this.currentWeekNumber === this.getWeekNumber(new Date())) {
fistDayOfTheWeek = new Date();
} else {
fistDayOfTheWeek = this.getDateOfWeek(week, year);
}
let sunday = new Date(fistDayOfTheWeek);
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
const dates = [];
const diff = sunday.getDate() - fistDayOfTheWeek.getDate();
for (let i = 0; i <= diff; i++) {
const upDate = new Date();
upDate.setDate(fistDayOfTheWeek.getDate() + i);
dates.push(upDate);
}
console.log(dates)
return dates;
},
So apperantly my dateSet function works like if it is not monday then show the dates from today to sunday and from next week from monday to sunday. But what is wrong in this function is it doesnt push when the month is changed. So for 4 weeks console.log(dates) displays:
[Tue Aug 10 2021 16:22:43 GMT+0200 (Central European Summer Time),
Wed Aug 11 2021 16:22:43 GMT+0200 (Central European Summer Time), Thu
Aug 12 2021 16:22:43 GMT+0200 (Central European Summer Time), Fri Aug
13 2021 16:22:43 GMT+0200 (Central European Summer Time), Sat Aug 14
2021 16:22:43 GMT+0200 (Central European Summer Time), Sun Aug 15
2021 16:22:43 GMT+0200 (Central European Summer Time)]
[Mon Aug 16 2021 16:22:46 GMT+0200 (Central European Summer Time),
Tue Aug 17 2021 16:22:46 GMT+0200 (Central European Summer Time), Wed
Aug 18 2021 16:22:46 GMT+0200 (Central European Summer Time), Thu Aug
19 2021 16:22:46 GMT+0200 (Central European Summer Time), Fri Aug 20
2021 16:22:46 GMT+0200 (Central European Summer Time), Sat Aug 21
2021 16:22:46 GMT+0200 (Central European Summer Time), Sun Aug 22
2021 16:22:46 GMT+0200 (Central European Summer Time)]
[Mon Aug 23 2021 16:22:47 GMT+0200 (Central European Summer Time),
Tue Aug 24 2021 16:22:47 GMT+0200 (Central European Summer Time), Wed
Aug 25 2021 16:22:47 GMT+0200 (Central European Summer Time), Thu Aug
26 2021 16:22:47 GMT+0200 (Central European Summer Time), Fri Aug 27
2021 16:22:47 GMT+0200 (Central European Summer Time), Sat Aug 28
2021 16:22:47 GMT+0200 (Central European Summer Time), Sun Aug 29
2021 16:22:47 GMT+0200 (Central European Summer Time)]
[]
As you see since after 3 weeks, the month will be changed to september and I think that's why it comes to an empty array.
I dont know if it is necessary but in any case here are the other functions that I used:
getDateOfWeek(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
return ISOweekStart;
}
getWeekNumber(date) {
const temp_date = new Date(date.valueOf());
const dayn = (date.getDay() + 6) % 7;
temp_date.setDate(temp_date.getDate() - dayn + 3);
const firstThursday = temp_date.valueOf();
temp_date.setMonth(0, 1);
if (temp_date.getDay() !== 4)
{
temp_date.setMonth(0, 1 + ((4 - temp_date.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstThursday - temp_date) / 604800000);
},
PS: currentWeekNumber is increasing everytime when the button is clicked.
Your issue is here:
const diff = sunday.getDate() - fistDayOfTheWeek.getDate();
when you get to the end of the month of say August, the next Sunday is 5 Sep and the first day of the week is 30 August, so diff is -25 and in the test:
for (let i = 0; i <= diff; i++) {
i is less than diff from the start so nothing is added to the array.
One fix is to get the number of days until the next Sunday and iterate for that many days, e.g.
// Return an array of dates from tomorrow until the
// following Sunday.
function getDatesToSunday(date = new Date()) {
// Copy date so don't affect original
let d = new Date(+date);
// Get the number of days until the next Sunday
let count = 7 - d.getDay();
// Create array of Dates
let dates = [];
while (count--) { 
dates.push (new Date(d.setDate(d.getDate() + 1)));
}
return dates;
}
console.log('Given Sun 29 Aug 2021:');
getDatesToSunday(new Date(2021, 7, 29))
.forEach(d => console.log(d.toDateString()));
console.log('Rest of this week, or next if today is Sunday:');
getDatesToSunday()
.forEach(d => console.log(d.toDateString()));
If the supplied date is Saturday, the above returns an array of just Sunday. If the supplied date is Sunday, it returns an array of the following Monday to Sunday, etc.
If you want to get multiple weeks of dates, add a second parameter, say weeks that defaults to 1, then add (weeks - 1) * 7 to count before the while loop. Test weeks first to ensure it's 1 or greater (starting a decrementing while loop with a negative number is not a good idea).
Or you can just keep adding days until Sunday:
const getDatesToSunday = (date = new Date()) => {
// Setup
let year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
dates = [];
// Add dates from tomorrow until Sunday
do {
dates.push(new Date(year, month, ++day));
} while (dates[dates.length - 1].getDay());
return dates;
};
getDatesToSunday().forEach(d=>console.log(d.toDateString()));

Javascript Array unshift new Date subtracting 1 Day

I am getting some strange results from the following code:
a = [];
a[0] = new Date();
console.log("1 Element Added: "+a.length + " - " + a.toString());
//"1 Element Added: 1 - Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"
a.unshift(new Date(new Date(new Date().setDate(a[0].getDate() - 1))));
console.log("First Unshift: "+a.length + " - " + a.toString());
//"First Unshift: 2 - Sat Jun 01 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"
a.unshift(new Date(new Date(new Date().setDate(a[0].getDate() - 1))));
console.log("Second Unshift: "+a.length + " - " + a.toString());
//"Second Unshift: 3 - Fri May 31 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sat Jun 01 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"
a.unshift(new Date(new Date(new Date().setDate(a[0].getDate() - 1))));
console.log("Third Unshift: "+a.length + " - " + a.toString());
//"Third Unshift: 4 - Sun Jun 30 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Fri May 31 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sat Jun 01 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"
Same code works 1st and 2nd time, but the 3rd run gives an unexpected result - it should be Thu May 30 2019, not Jun 30 2019 Can someone tell me what I'm doing wrong here?
Thanks in Advance.
The innermost new Date() always makes a Date instance in June. When you set the day-of-month to 30, you're forcing the date to June 30th, not May 30th.
Calling .setDate() can change the month, but only when the day-of-month is something that doesn't make sense, either smaller (zero or negative) or bigger (like 33). Since 30 is indeed a real day in June, the month doesn't change.
#Pointy and #Titus have already explained why the code does not work as you expected. Here I leave your code modified to react as you wanted:
a = [];
a[0] = new Date();
console.log("1 Element Added: "+a.length + " - " + a.toString());
//"1 Element Added: 1 - Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"
a.unshift(new Date(a[0]));
a[0].setDate(a[0].getDate()-1);
console.log("First Unshift: "+a.length + " - " + a.toString());
//"First Unshift: 2 - Sat Jun 01 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"
a.unshift(new Date(a[0]));
a[0].setDate(a[0].getDate()-1);
console.log("Second Unshift: "+a.length + " - " + a.toString());
//"Second Unshift: 3 - Fri May 31 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sat Jun 01 2019 12:13:35 GMT-0400 (Eastern Daylight Time),Sun Jun 02 2019 12:13:35 GMT-0400 (Eastern Daylight Time)"
a.unshift(new Date(a[0]));
a[0].setDate(a[0].getDate()-1);
console.log("Third Unshift: "+a.length + " - " + a.toString());

How to add dates between two dates in an array using Javascript or PHP?

I'm setting up a Graph using CanvasJS. Everything working fine. But in dates array, if there are no dates between from date object date: 23-7-2019 09:00 AM, value: 20 to date object date: 13-10-2019 11 AM, value: 25 the graph showing a straight line between these to dates. So I want to add dates for each day between those dates and want to set the value as null. so that graph will show the empty gaps instead of straight line.
So earlier I added value as null if the values or negative values. I have added the code below.
var mydatapoints4 = [];
for(var k=0; k< list_values.length; k++){
var tk= list_values[k].x;
var uk = list_values[k].y;
if(uk > 0){
mydatapoints4.push({x: new Date(tk), y: uk});
}
else{
mydatapoints4.push({x: new Date(tk), y: null});
}
};
So My datapoints 4 array is like this
0: {x: Fri Apr 06 2018 22:30:00 GMT-0500 (Central Daylight Time), y: 93.9}
1: {x: Sat Apr 07 2018 09:00:00 GMT-0500 (Central Daylight Time), y: 69.3}
2: {x: Tue Apr 10 2018 10:00:00 GMT-0500 (Central Daylight Time), y: 71.2}
3: {x: Wed Apr 11 2018 11:00:00 GMT-0500 (Central Daylight Time), y: 67.2}
I want the output of the array like this.
0: {x: Fri Apr 06 2018 22:30:00 GMT-0500 (Central Daylight Time), y: 93.9}
1: {x: Sat Apr 07 2018 09:00:00 GMT-0500 (Central Daylight Time), y: 69.3}
2: {x: Sun Apr 08 2018 09:00:00 GMT-0500 (Central Daylight Time), y: null}
3: {x: Mon Apr 09 2018 09:00:00 GMT-0500 (Central Daylight Time), y: null}
4: {x: Tue Jun 10 2018 10:00:00 GMT-0500 (Central Daylight Time), y: 71.2}
5: {x: Wed Jun 11 2018 11:00:00 GMT-0500 (Central Daylight Time), y: 67.2}
I hope my question is clear to you, and may I know how can I do that? if you can help me it's a huge help to me.
Thanks for the support.

What's wrong with this javascript sort

I'm not getting the sort results I expect. What's wrong.
Here's the code:
data.sort(function(a,b){
return (Date.parse(a) - Date.parse(b));
});
for(var j = 0; j < data.length; j++){
var item = data[j];
console.log(j+") " +item.createdAt+":"+Date.parse(item.createdAt));
}
And here's the output:
0) Fri Jun 10 2016 16:58:26 GMT-0400 (Eastern Daylight Time):1465592306000
1) Tue Jun 07 2016 08:07:34 GMT-0400 (Eastern Daylight Time):1465301254000
2) Fri Jun 10 2016 15:57:44 GMT-0400 (Eastern Daylight Time):1465588664000
3) Fri Jun 10 2016 14:34:45 GMT-0400 (Eastern Daylight Time):1465583685000
4) Fri Jun 10 2016 14:22:02 GMT-0400 (Eastern Daylight Time):1465582922000
5) Fri Jun 10 2016 11:14:34 GMT-0400 (Eastern Daylight Time):1465571674000
6) Fri Jun 10 2016 10:03:56 GMT-0400 (Eastern Daylight Time):1465567436000
7) Fri Jun 10 2016 10:02:58 GMT-0400 (Eastern Daylight Time):1465567378000
8) Thu Jun 09 2016 16:32:29 GMT-0400 (Eastern Daylight Time):1465504349000
9) Thu Jun 09 2016 16:29:24 GMT-0400 (Eastern Daylight Time):1465504164000
As data is array of object and each object contains the createdAt property on which the array should be sorted, you need
data.sort(function(a, b) {
return (Date.parse(a.createdAt) - Date.parse(b.createdAt));
});
If the data is coming from server database, I'll suggest to get the data sorted on the date from the Database itself.
Tushar hit it on the head, if that is what you're looking to sort on. If you want to go further in depth about sorting on a particular value comparison you'll want to research the array prototype. You can find that here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

javascript date itialising date produces erroneous date

Why does
new Date(2016, 3, 30);
produce:
Sat Apr 30 2016 00:00:00 GMT+0100 (GMT Summer Time)
should it not be Wed Mar 30 2016 00:00:00 GMT+0100 (GMT Summer Time)
It is because
new Date(2016, 3, 30);
means
year: 2016
month: 3 - 0: jan, 1: feb, 2:mar, 3: april
day: 30
Just do this:
new Date(2016, 2, 30);

Categories

Resources