Require assistance in accurately assigning a date to a Date[] in Typescript Array without altering current elements

In my current code, I have a loop that verifies if a date is a holiday and then adds it to an array. The issue I'm facing is that whenever I assign a new element to the array, all previous data in the list gets updated to the latest element. Here's a glimpse of the problem:

if (
          this._dateHelperService.isBusinessDay(temporalDate) &&
          !this._dateHelperService.isHoliday(temporalDate)
        ) {
          mNumberOfDays += 1;
          console.log(temporalDate.toDateString());
          console.log('entre')
          let tmpDate: Date[] = [...result.datesToPaint, temporalDate];
          result.datesToPaint = tmpDate;
          console.table(result.datesToPaint)
          // console.log(mNumberOfDays);
        }
        // re creating the date using a helper service
        if (mNumberOfDays !== numberOfDays) {
           temporalDate = 
           this._dateHelperService.addDays(temporalDate,1);
        }

        // helper service:
        addDays(date: Date, days: number): Date {
            date.setDate(date.getDate() + days);
            return date;
        }

This issue could be due to the pointer I'm using for the global list result.datesToPaint at the beginning of the method. I attempted to use the spread operator and temporarily assign the date to another variable, but it didn't resolve the problem. Any assistance on this matter would be greatly appreciated!

https://i.stack.imgur.com/mBKtc.png

Answer №1

Big shoutout to @Tobias S. for the helpful tip! I made a simple adjustment to my addDays function:

addDays(date: Date, days: number): Date {
    return new Date(date.setDate(date.getDate() + days));
  }

:) Reminder to be cautious when working with date arrays!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Docker: CORS policy is blocking access to XMLHttpRequest

After creating an ASP.NET Web Application (.NET Framework) project in Visual Studio 2022 and adding a web service to it, everything seemed to work fine when testing the web service call on Local IIS. However, things took a different turn when I tried runni ...

Execute operations on element itself rather than the output of document.getElementbyId

I encountered an issue involving an HTML element with the ID of BaseGridView. When I call a function directly on this element, everything works perfectly. However, if I use document.getElementById() to retrieve the element and then call the function, it do ...

In ReactJs, what is the best way to load a new component when a button is clicked?

In ReactJs, I have developed a main component known as MainPage using Material-UI. import React from 'react'; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; import CssBaseline from & ...

Numerous attributes housed within a single element

In my project, I have set up a Store using Angular and NgRx 13. Within my SharedModule, I define components including selectors which load content into the store to prevent redundant API calls. https://i.stack.imgur.com/sr3nl.png This approach is impleme ...

Populate your website with both a Bootstrap Popover and Modal for interactive user engagement through hover

Here's the situation: I want to showcase a user's name with a popover that reveals a snippet of their profile information. I've got that part down, where it dynamically generates and displays the popover content as needed. The popover functi ...

Using AngularJS and D3 to create a custom directive that allows for multiple instances of D3 loading within Angular applications

After creating an angular directive for a d3 forced-directed graph and using the code provided here, I encountered some issues with multiple loads. The directive seemed to load six times each time it was initialized, causing performance problems. To addres ...

Formik struggles to retrieve the chosen value from a dropdown selection

I'm currently using react, but I'm having trouble incorporating the selected select into the form data in Formik. Here is my form: <Card.Body> <Formik validationSchema={signUpS ...

Having issues with incorporating a component into another component in VueJS

Having spent approximately 30 hours on diving into VueJS, I am encountering some difficulties when it comes to using a component within another component. Seeking assistance from someone knowledgeable in this area to provide me with some clarification. Pr ...

Repeated information displayed in modal pop-ups

HTML <a class="btn" data-popup-open="popup-1" href="#">More Details</a> <div class="popup" data-popup="popup-1"> <div class="popup-inner"> <h2>Unbelievable! Check this Out! (Popup #1)</h2> ...

What is the reason behind the jQuery JSON parser requiring double escaping for backslashes?

I'm struggling to comprehend a strange aspect of the JSON data format. Here's the issue: I have a string with a Windows directory path, where backslashes are escaped. However, the jQuery JSON parser seems to require double escaping for some reas ...

Maintain the active menu open when navigating to a different page on the website

My website has a dropdown menu, but whenever I click on a submenu link, the new page opens and the menu closes. However, I want the active menu to remain open on the new page of the website! To demonstrate what I have tried in a simple way, I created an e ...

Obtain the identification number and full name from the typeahead feature

I am able to retrieve the name and ID, but I am only able to display the name. I have attempted using update and afterslected methods. Currently, I have this code which works well, however, it only fetches the name! $('input.typeahead').typea ...

Error detected in Deno project's tsconfig.json file, spreading into other project files - yet code executes without issues?

I am working on a Deno project and need to utilize the ES2019 flatMap() method on an array. To do this, I have created a tsconfig.json file with the following configuration: { "compilerOptions": { "target": "es5", ...

The value of Angular Input remains unchanged within a FormArray

I am experiencing an issue with the Sequence No in my PreprocessingForm's FormArray. When I add a new row, the Sequence No does not change as expected. <tr class="mat-row" *ngFor="let dynamic of PreprocessingForm.controls.arithmeticI ...

jQuery unable to find designated elements in uploaded templates

I have a specific route linked to a specific controller and view: app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/create', { templateUrl: 'partials/form/form.html', controlle ...

Next.js is able to generate a unique URL that strictly handles code execution without any visual elements

Currently, I am in the process of developing a new website using NextJS. One issue that has come up involves a password reset verification endpoint. After a user initiates a password reset, it is sent to the API for processing and then redirected back to ...

Having trouble running the script, chrome error with message passing?

I've hit a roadblock while working on my Chrome extension and could use some assistance. The main issue I'm facing is getting the script to run when activated by the user through an on/off switch in the popup window. It seems like there might be ...

What steps can I take to enhance the efficiency of this JavaScript DOM data manipulation algorithm?

Purpose I am working with a DOM that contains around 70 elements (divs with content). I have the need to move and toggle the display of these divs frequently and rapidly. Speed is crucial in this process. The trigger for moving and toggling these divs is ...

Display the returned view following an AJAX request

Currently, I am trying to search for a specific date in the database using ajax to trigger the function. However, I am encountering a 404 error when I should be receiving the desired outcome, and the ajax call is entering an error mode. Here is the snippet ...

Chaining promises: The benefits of attaching an error handler during Promise creation versus appending it to a variable containing a promise

function generatePromise() { return new Promise((resolve, reject) => { setTimeout(reject, 2000, new Error('fail')); }); } const promise1 = generatePromise(); promise1.catch(() => { // Do nothing }); promise1 .then( ...