Eliminate set of dates utilizing a different set of dates

Utilizing the MultipleDatePicker plugin to enable selection of multiple dates within a year. I have incorporated a checkbox feature that, when checked, will automatically mark all Sundays in the calendar.

However, an issue arises when unchecking the checkbox. It fails to deselect all previously selected Sundays in the calendar. To troubleshoot this problem, I implemented the following code snippet utilizing getTime():

var selected = $scope.selectedDates;

for (var i = 0; i < $scope.selectedDates.length; i++) {
    var date1 = new Date(selected[i]).getTime();
    console.log('date1[' + i + '] = ' + date1 + ' ' + moment($scope.selectedDates[i], 'MM-DD-YYYY'));
    for (var j = 0; j < sundays.length; j++) {
        var date2 = new Date(sundays[j]).getTime();
        console.log('date2[' + j + '] = ' + date2 + ' ' + moment(sundays[j], 'MM-DD-YYYY'));
        if (date1 === date2) {
            selected.splice(i, 1);
            break;
        }
    }
}

After reviewing the comparisons made between the dates, some appear to match while others do not. Can you identify the flaw in the code?

For further investigation and demonstration of the issue, access the Plunker link here.

Answer №1

The issue arises when an item is removed from an array, causing the index i to increase within a loop and potentially skip over an element. A solution to this problem is to decrement the value of i after each removal:


    // ...
    if (date1 === date2) {
        selected.splice(i, 1);
        i--;
        break;
    }

Answer №2

Oops, a small oversight occurred; the issue lies in forgetting to decrement i. Here is the corrected code:

for (var i = 0; i < $scope.selectedDates.length; i++) {
    var date1 = new Date(selected[i]).getTime();
    console.log('date1[' + i + '] = ' + date1 + ' ' + moment($scope.selectedDates[i], 'MM-DD-YYYY'));
    for (var j = 0; j < sundays.length; j++) {
        var date2 = new Date(sundays[j]).getTime();
        console.log('date2[' + j + '] = ' + date2 + ' ' + moment(sundays[j], 'MM-DD-YYYY'));
        if (date1 === date2) {
            selected.splice(i, 1);
            i--;
            break;
        }
    }
}

Answer №3

It appears that decrementing the variable i was overlooked in your implementation of the splice method.

 if (date1 === date2) {
    selected.splice(i, 1);
    i = i - 1;
    break;
 }

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

Find out which way the user is scrolling in your React js application

I'm struggling to determine whether the scroll event is moving up or down, and I haven't been able to find a solution yet. import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; const Nav ...

Determine the difference between a CSS selector string and an XPath string

Developing a compact querying module (using js) for html is my current project, and I aim to create a versatile query(selector) function that can handle both css selectors and XPath selectors in string form. My dilemma lies in determining whether a given ...

How can I identify where a Mesh and Particle System intersect in Three.js?

I have a unique setup where I have a particle system utilizing sprites, housed in an Object3D akin to the "interactive / points" example from three.js. Additionally, I have a simple sphere mesh that tracks my cursor's movements. Check out the example ...

Can you explain the distinction between export/import and provide/inject in Vue3?

Can you explain the difference between export/import and provide/inject in Vue3? // parent const data = provide('data', ref(0)) // child const data = inject('data') // parent export const data = ref(0) // child import { data } from & ...

Looking for guidance on how to specify the angular direction in the ng-repeat

I am facing a challenge with the structure of my ng-repeat directive and I am having trouble navigating through it. Here is a representation of the data in array format JSON style {"data":[ ["sameer","1001", [ {"button_icon": ...

Experiencing an issue with the countdown timer while utilizing react-countdown library

Currently, I am in the process of creating a countdown timer that allows users to input time in minutes and start or stop the clock. However, I have encountered two challenges: I defined a state running to determine if the clock is running, and based on t ...

Using jQuery to display checkbox text even when it is not directly adjacent to the checkbox

I'm struggling to display the checked value text as shown in the image without any refresh or click. Can anyone offer assistance? This is my PHP dynamic form: <div class="products-row"> <?php $tq=$conn->query("select * from os_tiffen ...

Trouble organizing a collection of destinations based on their geolocation and proximity

To address this issue, my approach has been to feed variables into the value attributes of an option list and then sort it based on these values. When manually assigning values, everything works smoothly, for example: <option id="link1" value="1">A& ...

`Python automation for seamless HTTP browsing and HTML document generation`

My weekly routine at work involves printing out Account analysis and Account Positions for more than 50 accounts every Monday. I have to navigate through the page, select "account analysis", input the account name, format the page for printing, print the o ...

increasing the size of a picture without resorting to a pop-up window

Struggling to implement a product details tab within a table that features a clickable image. When the image is clicked, it should enlarge but the width doesn't adjust accordingly. I'm using bootstrap 5.3 and can't seem to identify the root ...

Forking a Node.js child process to assign it CPU affinity

Looking to utilize the child_process.fork function in Node.js for spawning a new process. This example is also applicable with the spawn function. To optimize CPU usage and make sure that these child processes are distributed evenly across all cores of th ...

Transferring data between jQuery and other global JavaScript variables

I'm facing a challenge when trying to make functions I created in jQuery access JavaScript values defined elsewhere. For instance, I have a function set within my jQuery code. var parentImg = ''; //global variable. $(document).change(funct ...

Error: Class cannot be loaded by React Webpack loader

I'm encountering an issue with my two typescript packages - a React application and an infrastructure package. The React app has a dependency on the infrastructure package (currently linked via npm). After adding a new class to the infrastructure pack ...

Inserting multiple rows in MySql using JavaScript through a URL pathUnique: "

Hello there! I am currently attempting to send an array of objects to my MySql Database via an API endpoint. Below is the code snippet from my API: app.get("/orderdetails/add", (req, res) => { const { item__, Qty_Ordered, Unit_Price, ...

Encountered a runtime error while processing 400 requests

Current Situation: When authenticating the username and password in my Ionic 2 project using WebApi 2 token authentication, a token is returned if the credentials are correct. However, a 400 bad request error is returned if the credentials are incorrect. ...

Preserve dropdown selections in JavaScript even when the page is refreshed

Two dropdown menus are present, where the second dropdown menu is dependent on the selection made in the first dropdown. However, after refreshing the page following an ajax update, the second dropdown does not retain the previously selected choice. How ...

Tips for dynamically resetting the dataTable

When I create a datatable and add rows dynamically based on the selected option, I encounter an issue where I need to reinitialize the dataTable every time the option is changed. To address this, I have placed the reinitialization code inside the $("#selec ...

What is causing the question mark symbol to appear at the beginning of my ajax response?

Below is my JavaScript code: $('#tags').select2({ tags: true, tokenSeparators: [','], createSearchChoice: function (term) { return { id: $.trim(term), text: $.trim(term) + ' (new tag)&ap ...

The function this.$set is failing to update an array in VueJS

I am facing an issue where the console log shows me the updated array xyz, but when I try to print it in the DOM using {{xyz}}, it does not update. Can anyone shed some light on why this might be happening? data() { return { xyz: [] } }, met ...

The initial attempt to use autocomplete with Jquery UI is not functioning as expected upon entry

I'm facing a frustrating issue that's driving me crazy. I'm not an expert in javascript, but I believe the solution is simple. I'm using jQuery UI autocomplete with data retrieved from Ajax. The problem is, I only get the desired resul ...