Beware of overwriting the first element in an array when creating it with a while loop in JavaScript or AppsScript

I am attempting to generate an array containing all dates within a specified time frame. To test this, I have chosen Feb 9 - Feb 13 as the date range. Ideally, the resulting array should display [Feb 9, Feb 10, Feb 11, Feb 12, Feb 13]. Upon revisiting an older post, I discovered the method of using New Date() to create new Date objects each time to avoid ending up with a repetitive array like [Feb 13, Feb 13, Feb 13, Feb 13, Feb 13]. However, I am facing an issue where the very first element I push to the array is being overwritten. The output currently shows [Feb 10, Feb 11, Feb 12, Feb 13, Feb 13]. Within my while loop, I've included a print statement to monitor the array after every push, which indicates that the initial element is being replaced. Any insights on why this is occurring and how I can achieve my desired array would be greatly appreciated. Thank you!

Below is the code snippet I am utilizing:

var Current_Date = new Date(Date_start); // Starting from Feb 9 
Current_Date = new Date(Current_Date.setHours(Current_Date.getHours() - 24)); // Updating to Feb 8
var Billing_Dates = []

while (Current_Date.valueOf() <= Date_end.valueOf()) {
    Current_Date = new Date(Current_Date.setHours(Current_Date.getHours() + 24));
    Billing_Dates.push(Current_Date);
    Logger.log(Billing_Dates)
}

Simplified Output (showing array status after each push):

[Feb 09]
[Feb 10, Feb 10]
[Feb 10, Feb 11, Feb 11]
[Feb 10, Feb 11, Feb 12, Feb 12]
[Feb 10, Feb 11, Feb 12, Feb 13, Feb 13]

View Image of the Actual Output (including array status after each push)

Answer №1

When you perform the action

Add_Bill_Dates(Billing_Dates)

you are actually adding a reference to the date, rather than the date itself. This means that any changes made to the original date will also reflect in the dates stored in your array. Hence, the last two dates in your array always appear identical. The following line of code demonstrates this concept:

Billing_Date = new Date(Current_Date.setHours(Current_Date.getHours() + 24)); 

By creating a new reference using new Date(), you end up modifying only the last two elements in the array.

To rectify this issue, ensure you create a fresh reference when storing in the array :

Billing_Dates.push(new Date(Current_Date))

Answer №2

Instead of continuously manipulating date references in place, a more efficient approach would be to create a new date object for each instance, like this:

const totalDays = 7
const oneDayMs = 24 * 3600 * 1000;
const allDates = [];
const startDate = new Date();

for (let i=0; i < totalDays; i++){
  const currentDate = new Date(startDate.getTime() + i * oneDayMs);
  allDates.push(currentDate.toString())
}

console.log(allDates)

Answer №3

function createArrayOfDates(startDate = '2/9/2021', endDate = '2/13/2021') {
  let dateArray = [];
  let startDay = new Date(startDate);
  let endDay = new Date(endDate);
  let increment = 0;
  do {
    dateArray.push(new Date(startDay.getFullYear(), startDay.getMonth(), startDay.getDate() + increment++));
  } while (new Date(dateArray[dateArray.length - 1]).valueOf() < endDay.valueOf());
  let formattedDates = dateArray.map((date) => {return Utilities.formatDate(new Date(date), Session.getScriptTimeZone(), "MMM dd")});
  Logger.log(formattedDates);
}

Execution log
12:28:30 PM Notice  Execution started
12:28:30 PM Info    [Feb 09, Feb 10, Feb 11, Feb 12, Feb 13]
12:28:30 PM Notice  Execution completed

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

Validation based on the condition of the request body in Express using express-validator

I have a specific route in place for handling different scenarios, with only minor variations in logic between them. To keep things streamlined, I have decided to utilize a single endpoint and differentiate between cases using the parameter 'type&apos ...

Utilizing React: Incorporating classes to elements with innerHTML

Is there an efficient way to determine if a table cell contains innerHTML and apply a class accordingly? I have a large table with numerous cells that need to be handled dynamically. The cell content is set using dangerouslySetInnerHTML, as shown below: ...

What is the best way to extract the text from the first visible `<td></td>` table row using jQuery?

In this particular scenario, there is a table included: <table id="table"> <thead> <tr> <th>Name</th> <th>Course</th> </tr> </thead> <tbody> <tr style="display:none"> ...

What steps can I take to prevent the "onclick" event from triggering multiple times?

I'm struggling to create a button that, when clicked, reveals a message input area. I am using the "onclick" attribute in the HTML and I want to ensure that the button is only clickable once to avoid generating multiple textareas on subsequent clicks. ...

What is the best way to utilize Angular to conceal an image until it is fully loaded?

I am currently utilizing angularjs to dynamically generate images. My goal is to hide or show a placeholder for each <img> element until it fully loads. Is it possible to achieve this directly in my html, or should I handle it through the controlle ...

Creating gulp tasks that are compatible across different platforms, particularly using gulp-shell

I'm currently facing an issue with running gulp tasks on Windows. The shell commands that work perfectly fine on Linux are not recognizing environment variables using the $var syntax (equivalent to %var% in Windows). Do I need to create a separate gul ...

Obtain a collection of a specific property from an array of objects that each contain that property

I am working with an object that looks like this: public class SavedFileInfo { public String Address; public Int32 DataPort; public Int32 AudioPort; public String Description; public String Filename; } Within my collection of these ob ...

The useEffect React Hook is missing a dependency: 'fetchTracker'. Please make sure to add it to the dependency array or consider removing it

I recently encountered a challenging issue with one of my projects. The file in question is responsible for tracking data, which is then displayed on a map within an application. Despite my attempts to find a solution on StackOverflow, I have not found an ...

In a carousel slider, the height and width of divs are not set to specific dimensions

For a code snippet, you can visit this link: here The html: <html lang="en"> <head> <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet"> <link href="https://ma ...

Will terminating a Google Cloud Storage stream impact network usage?

As part of my project, I am developing a media server that will serve streamable audio files. To reduce the number of requests to Google Cloud Storage, I have implemented a caching system. However, one issue I've encountered is that Chrome sends two ...

Be warned: Babel has detected a duplicate plugin or preset error

Currently, I am enrolled in a React course on Frontend Masters. As part of the course, we were tasked with modifying the Babel config to allow state instantiations like: state = {index: 0} in class components. However, when I executed the command: npm i ...

Error message: "React Component not identified"

I am following [this React tutorial][1] and facing an issue right from the start as my React components are not being identified. Here is a snippet of my code: import React from 'react'; import {BrowserRouter as Router, Route, Routes} from "react ...

The issue of asynchronous behavior causing malfunctioning of the PayPal button

import { PayPalButton } from 'react-paypal-button-v2' <PayPalButton amount={total} onSuccess={tranSuccess} /> const tranSuccess = async(payment) => { c ...

Bootstrap 5.5.2 facing transition issues on bundle.js

Recently, I attempted to incorporate zoom.js into my project to enable image zoom functionality similar to that of the medium website. After linking both the CSS and JS files, it seemed to be working properly. However, I encountered an issue where the tra ...

Utilize mapping function to merge arrays

Currently facing an issue with no clear solution in sight. When making API calls via a map, I am able to successfully log all results individually. However, my challenge lies in combining these results into a single array. var alpha = ['a', &apo ...

The output from the Node.js child_process.exec command returned null for stdout, yet stderr was not empty

I'm currently working with a simple code that runs java -version in the command line to check if Java is installed on the user's system. Interestingly, when I execute this code, the stdout does not display anything, but the stderr shows the expe ...

Troubleshooting a NextJS and ExpressJS error related to on-demand entry pinging

A challenge arose as I implemented NextJS with a custom server using Express. The issue surfaced while defining routes in Express. Defining Express routes as shown below resulted in errors: app.get('/:username', handle.profile) app.get('/: ...

Implementing a node.js application deployment with pm2 to ensure zero downtime

While there are countless tutorials on developing chat applications using socket.io and node.js, the event-driven advantage of Node is undeniable for building chat apps. However, a recent thought crossed my mind - how can I ensure the sustainability of my ...

What is the best way to transfer parameters from the Vue root to a component?

Currently, I am attempting to transfer a string value from index.cshtml to the main Vue element. The specific parameter I want to pass is: userId Location: Index.cshtml (this is where the parameter is obtained) @using Microsoft.AspNetCore.Identity @inje ...

Using JavaScript to modify elements that have been dynamically generated

This is the JavaScript code I am working with. I am dynamically adding a list (`ul`) to my container div called `columns`. However, when I try to apply some functions to each new list item (`li`), nothing seems to happen. The same code works perfectly fine ...