What is the most efficient way to add or remove Date objects from arrays?

Struggling to update a calendar using the Datepicker component with Vue.js, I encountered some issues with adding and deleting items (specifically Date objects)

I have written two javascript functions: one for adding new Dates to an array, and another for removing specific dates from the same array. The problem arises when trying to add a date and then delete it without reloading the website, as the function returns -1 when searching for the index of the date in the array.

addDate: function(event) {
   var fecha = document.getElementById("inputFecha").value;
   var fecha2 = new Date(fecha);
   availableDates.push(fecha2);
},
deleteDate: function(event) {
   var collection = availableDates,
      d = new Date(event.getFullYear(), event.getMonth(), event.getDate()),
      idx;
   idx = collection.map(Number).indexOf(+d);
   if(idx!=-1){
      availableDates.splice(idx,1);
   }
}

Here are some of the initial dates created in the file:

var availableDates = [];
availableDates.push(new Date(2019, 2, 29));
availableDates.push(new Date(2019, 2, 30));
availableDates.push(new Date(2019, 2, 28));

The goal is to enable adding and deleting functionality without needing to refresh the website.

Answer №1

When you use the code new Date(2019, 2, 30), the date created is 2019-03-30T00:00:00 in the timezone set on your device.

It's important to note that if you were to use new Date("30/3/2019"), it would create 2019-03-30T00:00:00Z which refers to UCT/UTC/GMT/Zulu time. This may result in an error if your timezone is not +0.

If inputFecha is an <input type="date">

addDate: function(event) {
    var fecha = document.getElementById("inputFecha").valueAsDate;
    var fecha2 = new Date(fecha.getFullYear(), fecha.getMonth(), fecha.getDate());
   availableDates.push(fecha2);
},

In order to demonstrate that the code works, here is a dummy example since no Minimum Complete Verifiable Example (MCVE) was provided:

const availableDates = [];
let something = {
  addDate: function(event) {
    var fecha = document.getElementById("inputFecha").valueAsDate;
    var fecha2 = new Date(fecha.getFullYear(), fecha.getMonth(), fecha.getDate());
    availableDates.push(fecha2);
    console.log(availableDates);
  },
  deleteDate: function(event) {
    var collection = availableDates,
      d // = new Date(event.getFullYear(), event.getMonth(), event.getDate()),
    
    // dummy code to test
    var fecha = document.getElementById("inputFecha").valueAsDate;
    d = new Date(fecha.getFullYear(), fecha.getMonth(), fecha.getDate());
    // end dummy code
    
    const idx = collection.map(Number).indexOf(+d);
    if (idx != -1) {
      availableDates.splice(idx, 1);
    }
    console.log(availableDates);
  }
}
availableDates.push(new Date(2019, 2, 29));
availableDates.push(new Date(2019, 2, 30));
availableDates.push(new Date(2019, 2, 28));
console.log(availableDates);
document.querySelectorAll('.butt').forEach(btn =>
  btn.addEventListener('click', something[btn.id])
);
<input type="date" id="inputFecha">
<input type="button" class="butt" id="addDate" value="add">
<input type="button" class="butt" id="deleteDate" value="remove">

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

Is there a way to transfer a value from one JS function to another in Node.js?

I am struggling to retrieve the return value from a JavaScript function in Node.js and pass it back in a POST method within my server file. Despite my efforts, I keep receiving an undefined result. What could be causing this issue? My objective is to retur ...

Keeping a while loop going with JSON object stored as array within another array

The issue I am facing: While joining tables, I encounter a problem where some of the tables contain multiple data that needs to be fetched. However, my JSON object is only retrieving one set of data. This is likely happening because my while loop goes thr ...

Customize the appearance of the Vue.js datepicker starting from today's date

I am currently using the vue-datepicker component to display a date input field in my form. I want to set the default date to the current day and disable the selection of past dates. Additionally, I need to change the language of the component but it seems ...

The program encountered an issue trying to access the property 'map' of an undefined element in ReactJS utilizing AJAX

Displaying an array in a table retrieved from an AJAX request in Action while utilizing Redux. class IncomeProfile extends Component { constructor(props) { super(props) } componentDidMount() { this.props.IncomeListProfile(); } render ...

hide bootstrap confirmation when clicking off of it

I'm facing an issue with the bootstrap confirmation plugin. I want to close all confirmations when the user clicks outside of the confirmation pop-up. However, the current implementation is causing the confirmation to close everytime there is a click ...

Sending a null variable via an AJAX post request from jQuery to PHP

Query: <table> <tr> <td id="percentage">Percent:&nbsp; <?php echo $percent; ?> %</td> </tr> </table> <div class="box-footer" style="float: right"> <a href="<?php echo base_url(); ?>stu ...

Closing md-tooltip automatically after a specified timeout period

I've set up md-chips in Angular material with the following configuration: <md-chips md-chips-disable-input ng-model="session.participants"> <!-- Chip removal button template --> <button md-chip-remove class ...

Angular JS page in its purest form

I have successfully developed a single-page application using AngularJs. However, when I visit the main page of my application hosted on the Heroku server, for a brief moment, all the images and text appear in a raw state at the top left corner of the bro ...

I am looking to efficiently sort and structure information from a CSV file using PHP

I am in possession of a csv file containing my vehicle inventory and I am seeking guidance on how to arrange this inventory based on the duration for which I have owned each vehicle. My desired output is as follows - 30 cars 0-30 days old 25 cars 31-60 ...

Error Encountered: Module Missing Following NPM Installation

I just started using Node and ran into an issue after setting up a new node project with NPM init. I tried installing lodash by running the command: npm install lodash --save However, the command resulted in the following error: npm ERR! code MODULE_NOT ...

Assigning specific class names to elements within an array using JavaScript

Currently, I'm attempting to assign a unique className to option elements within a select element by utilizing a conditional if statement. The goal is to apply one class name to the first half of the array and a different class name to the second half ...

From milliseconds to hours: a straightforward conversion

Given a start date, time and end date, time, I am trying to calculate the total travel duration. The output is in milliseconds and needs to be converted into hours format. Despite attempting some solutions shared here, I haven't been successful. < ...

Creating a unique filter that combines and filters data from two separate API calls for

In my current scenario, I am making two different API calls using Axios in my application. The first call fetches a complete JSON file that populates a table, while the second call retrieves only categories. This setup is due to the complexity of the app, ...

Ways to avoid browser refresh when uploading files in React applications

I'm working with a simple file upload form in React using hooks. import React, { useState } from 'react'; import { FlexContainer } from '@styles/FlexContainer'; const TestUpload = () => { const [file, setFile] = useState<F ...

Notifying with Jquery Alert after looping through routes using foreach loop

I am trying to create a jQuery alert message that displays after clicking on a dynamically generated button in the view using a foreach loop. The issue I am facing is that only the first button in the loop triggers the alert, while the subsequent buttons ...

Utilizing relative URIs in Node.js request library

I've encountered an issue with my code where node.js is unable to resolve the url: const request = require('request') const teamURL = `/users/${user._id}/teams`; const req = request({ url: teamURL, json: true }, function(error, ...

Is React the ideal choice for implementing a shared state subscription mechanism in your project?

Trying to determine if this falls under the "pub/sub" pattern or a variation of it. The goal is to establish a shared state where different components can subscribe to it and only receive updates when the state changes. const useForceUpdate = () => useR ...

"Exploring the blend of VueJS, ExpressJS, and MySQL in architectural design - A deep dive into

What is the architectural structure of my Vue.js + Express.js + MySQL application? I am tasked with detailing the design of my app for a project, but I'm uncertain about what to name or classify it as. Vue.js (Frontend) Primarily focuses on managin ...

Angular foreach method encounters a syntax issue

When I use the getTotal.getValues() function to make a server call that returns values like "one", "two", "three" up to "nine", I am able to print them using console.log(res). However, I am facing an issue where I cannot push these returned values into t ...

Issue with CSV download box not showing up on Rails version 2.3.11

I've encountered an issue while trying to export a csv file with some data. I am using ajax call to select rows from the view table (jqGrid) and export them in a csv format. However, after a successful ajax call, the filtered data is displaying as an ...