What causes an array to accumulate duplicate objects when they are added in a loop?

I am currently developing a calendar application using ExpressJS and TypeScript. Within this project, I have implemented a function that manages recurring events and returns an array of events for a specific month upon request.

let response: TEventResponse[] = [];
    for (let i = 0; i < events.length; i++) {
        let e = events[i];
        if (!e.isPeriodical) {
            const event: TEventResponse = {
                beginning: e.beginTime,
                ending: e.endTime,
                title: e.title,
                description: e.description,
                place: e.place,
            };
            response.push(event);
        } else {
            let beginning = new Date(e.beginTime);
            const upperDate = new Date();
            upperDate.setFullYear(year);
            upperDate.setMonth(month + 1);
            upperDate.setDate(1);
            const lowerDate = new Date();
            lowerDate.setFullYear(year);
            lowerDate.setMonth(month);
            lowerDate.setDate(1);
            console.log(lowerDate);
            console.log(upperDate);

            let dateBoundary = undefined;
            if (e.dateBoundary) {
                dateBoundary = e.dateBoundary;
            } else {
                dateBoundary = upperDate;
            }
            console.log(dateBoundary);

            if (dateBoundary >= upperDate) {
                const periodicalEventsArr: TEventResponse[] = [];
                while (beginning <= dateBoundary && beginning < upperDate) {
                    if (beginning >= lowerDate) {
                        const event: TEventResponse = {
                            beginning: beginning,
                            ending: e.endTime,
                            title: e.title,
                            description: e.description,
                            place: e.place,
                        };

                        periodicalEventsArr.push(event);
                        console.log(periodicalEventsArr);
                    }
                    const n = e.repeatPeriod!;
                    switch (e.repeatPeriodUnit) {
                        case "DAY":
                            beginning.setDate(beginning.getDate() + n);
                            break;
                        case "WEEK":
                            beginning.setDate(beginning.getDate() + n * 7);
                            break;
                        case "MONTH":
                            beginning.setMonth(beginning.getMonth() + n);
                            break;
                        case "YEAR":
                            beginning.setFullYear(beginning.getFullYear() + n);
                            break;
                    }
                    console.log(periodicalEventsArr);
                }
                response.concat(periodicalEventsArr);
            }
        }
    }

    return response;

The main for loop functions correctly, but the inner while loop, intended to add a periodic event multiple times by adjusting the date each time, is exhibiting unexpected behavior.

Although the event appears to be added correctly initially (as shown in the first console.log(periodicalEventsArr)), subsequent iterations are modifying not only the 'beginning' value of the new event but also altering the same field in all previously added events (visible from the second console.log(periodicalEventsArr)). Consequently, the final array primarily consists of duplicates of the last added event.

This issue has puzzled me for some time now, and I would greatly appreciate any insights or guidance on where I may be going wrong.

Answer №1

The issue lies in consistently adding the same object, beginning, and altering its state each time, thereby affecting previous items in the array. To illustrate this problem clearly:

let beginning = new Date(); //creating a new date object
let myArray = []; //initializing a new array
myArray.push(beginning); //adding the created date to the array
console.log(myArray); //displays the current day 
beginning.setFullYear(2001); //changing the year of the date object
console.log(myArray); //reveals that the previously added item in the array also changed

To resolve this issue, a revised approach is necessary:

    let beginning = new Date(); //creating a new date object
    let myArray = []; //initiating a new array
    myArray.push(beginning); //adding the date to the array
    console.log(myArray); //displays the current day
    beginning = (new Date(beginning)).setFullYear(2001); //modifying the date object separately
    console.log(myArray); //demonstrates that the array item remains unchanged

To implement this solution in your scenario:

                        const event: TEventResponse = {
                            beginning: new Date(beginning), //cloning the date instead of referencing the same object
                            ending: e.endTime,
                            title: e.title,
                            description: e.description,
                            place: e.place,
                        };

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

Issue with file upload: The view is not refreshing in response to non-angular events

I am having an issue with my upload component where the view is not updating when the onchange event fires. Even though I can see the file names being logged, nothing is happening on the screen. My approach involves using a directive so that I can easily ...

An error occurs when trying to load data into a grid upon clicking, resulting in an Uncaught TypeError: Unable to access properties of undefined (specifically 'dataState')

I have implemented a grid in React using a specific library, and I want to populate the grid with data fetched from an API call when the user clicks on a button labeled Fetch Products. However, I encounter an error during debugging: Uncaught (in promise) T ...

Change the value of a single element in an array using a component in ReactJS

I'm attempting to pass an array value to a specific index in one component and then assign a desired value from the child component. I need it to work this way because I'm developing a survey app where the number of questions can vary. This is j ...

Creating nested for loops in Python can be achieved by defining a function that generates the desired loop structure

Programming in python3, I set out to create a program that could generate all possible combinations of 16 chords (for music composition) by choosing between a C chord and a G chord. The code I used to achieve this is as follows: chords = ['C', & ...

Is it possible to extract the value displayed on a Typography component in Material UI and store it in a state variable?

I'm currently facing an issue with mapping a data array onto material-ui Typography elements. Here's the code snippet: { array.map((item, id)=> <Typography key={id} value={item.name} />) } While this code successfully displays the val ...

Trouble with displaying cell content in ag-grid within an Angular application

I have implemented ag-grid in my Angular project and I am trying to redirect to a link when a specific cell is clicked. Currently, I have a new value coming from an API which is nested inside an object in an array. For example, the object is dto-> dat ...

Is there a way to execute Javascript in Django without revealing static files?

When setting up payments on my Django site using Stripe, I realized that the .js file is visible under Sources in the developer tools when inspecting elements on any browser. This presents a potential security risk as anyone can access this file. How can ...

Utilizing Angular Filter to compare the date in a JSON file with the current system date

<p id="appt_time" ng-if="x.dateTime | date: MM/dd/yyyy == {{todaysDate}}">DISPLAY IF TRUE{{todaysDate}} </p> Plunkr:https://plnkr.co/edit/r2qtcU3vaYIq04c5TVKG?p=preview x.dateTime | date: MM/dd/yyyy retrieves a date and time which results in ...

JavaScript asynchronous problem

When developing a simple Javascript function to validate user input for City and State, it encounters an issue with asynchronous behavior. The function checks if the user has entered values in the specified input fields and then proceeds to geocode the l ...

phpif (the current date is after a certain specific date, do

Can someone please help me solve this problem? I want to prevent echoing a variable if the date has already expired. Currently, my PHP code displays: Match 1 - April 1, 2015 Match 2 - April 8, 2015 What I need is for Match 1 to not be echoed if the cur ...

PhpStorm alerts users to potential issues with Object methods within Vue components when TypeScript is being utilized

When building Vue components with TypeScript (using the lang="ts" attribute in the script tag), there is a warning in PhpStorm (version 2021.2.2) that flags any methods from the native JavaScript Object as "Unresolved function or method". For exa ...

Building an array of objects using a foreach loop

i am struggling to create an array of objects from two input groups, each group consists of 3 inputs with data-side attributes set to left or right every input has a class named "elm" and a data-pos attribute set to a, b, or c <input class="elm-left elm ...

Trying to understand the strange behavior of HTML parsing with jQuery in Javascript and Firefox

I have been working on a script to parse an HTML page using jQuery. The script runs smoothly in Chrome, IE, and Safari, but I'm facing some unexpected behavior while testing it in Firefox (version 36.0.1). Here's the code snippet: $.ajax({ u ...

Trouble retrieving desired data from an array of objects in React Native

I'm having trouble retrieving values from an array of objects in my state. When I try to access the values, it only prints out "[Object Object]". However, when I stored the values in a separate array and used console.log, I was able to see them. Here ...

What is the optimal approach for moving the dashboard to a separate subdomain in a static Next.js-generated landing page?

Our current setup includes several static pages generated by Next.js using the command next build && next export These pages are hosted on AWS S3. I am wondering if we should create a new app for building a dashboard with Firebase authentication ...

I am experiencing an issue where the onChange event is not being triggered in my React application

I am currently in the process of creating a random football team picker and handling the database on my own. However, I seem to be encountering issues with the inputs. import React, { use, useRef, useState } from "react"; const fetchAll = async ...

I am experiencing an issue where a JSON string array is being converted into a C# List object, but each field of a Model inside the List is returning a "null

I have a string that contains JSON array data, and I'm attempting to convert it into a List of C# Model objects. Although the line of code I'm using shows the correct count with "objectList.Count," when I inspect the list during debugging, every ...

Translate CSS into JavaScript while maintaining selector understanding

I am interested in developing a tool that can read a .css file and generate a function that will accept an array of class names as input and output the corresponding styles for an element with those classes, represented as a JavaScript object. This tool wo ...

Getting real-time comments after they have been submitted in ReactJS

Is it possible to dynamically display newly added comments in real-time without refreshing the page after submitting them to the database through an API? Here's a snippet of the code I currently have: const PostWidget = ({ post }) => { ...

The Utilization of Callback Functions in CRUD Operations

I am curious about incorporating CRUD operations as callbacks while maintaining the Separation of Concerns. For instance, I have written a function that retrieves all users: UserService.js function getUsers(callback) { User.find(function(err, users) { ...