Reputation: 113
Im trying to empty the array below but it it just keeps piling onto it instead of actually emptying it. Any ideas why this happens?
displaytaken[];
Edit: Adding a StackBlits:
Im getting way to confused. With the Snippet/JQ and im changing to much to get a accurate answer out of this.
Issue now is that it actually works in the stackblitz so something els is asstray will be editing it to reach a working recreation
https://stackblitz.com/edit/angular-ivy-kdec3f?
Another Edit:
Im finding it hard to recreate the issue but on the stacklits youll notice a function called checkinbetween() in there is a array called : filteredArray
This is storing data even if i clear it despite changing it from const to var so its duplicating all outputs on my side
Screenshot to help show whats happening on my side:
As u can see I clear the array but then when I add to it again the old values are there still
Upvotes: 1
Views: 86
Reputation: 11466
You are using Typescript, which gives you the added advantages of using types. Also, I would advice you to start using immutablility.
Instead of populating some 'global' array, you should create functions for you that return you the data that you need:
// Instead of this
const myDateArray: Date[] = [];
for (const someValue of someOtherDateArray) {
if (some.condition()) {
myDateArray.push(someValue);
}
}
// Do this:
function getDateArray(otherDateArray: Date[]): Date[] {
return otherDateArray.filter(date => some.condition());
}
That way, you don't need to clear the date array, as a new one can be requested on the fly.
To get to your answer, I assume you are looping over a lot of date arrays, and displaying them as taken dates in an alert
box. here is how you can do that without clearing the array everytime:
const allTakenDates = [
[
new Date('2018-01-16'),
new Date('2018-03-26'),
new Date('2018-05-22'),
new Date('2018-12-01'),
new Date('2018-01-23'),
],
[
new Date('2019-01-16'),
new Date('2019-03-26'),
new Date('2019-05-22'),
new Date('2019-12-01'),
new Date('2019-01-23'),
],
[
new Date('2020-01-16'),
new Date('2020-03-26'),
new Date('2020-05-22'),
new Date('2020-12-01'),
new Date('2020-01-23'),
]
];
function getDatesAsString(dates: Date[]): string[] {
return dates.map(date => `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`);
}
for (const dates of allTakenDates) {
const formattedDates = getDatesAsString(dates).join();
alert('The following dates are taken: ' + formattedDates);
}
And here is a working example of that code.
Upvotes: 2