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

Having trouble accessing portlet resource URL from JavaScript in Liferay 6.2

I have been working with Liferay Portal 6.2 CE GA3 and I am facing an issue where I need to execute a custom portlet resource method from another portlet's JSP file. Below is the code snippet I am currently using. <a href ="#" onclick="myfunctio ...

SSL Offloading and Cross-Origin Resource Sharing

I am currently facing a challenge with my two applications located on separate servers. One acts as the frontend machine while the other serves as the backend API. Our setup involves SSL termination at the load balancer for security. The issue arises when ...

Tips for creating a smooth scrolling header menu on a standard header

<script> $(document).ready(function(){ $(".nav-menu").click(function(e){ e.preventDefault(); id = $(this).data('id'); $('html, body').animate({ scrollTop: $("#"+id).o ...

Calculate the total value of a specific field within an array of objects

When pulling data from a csv file and assigning it to an object array named SmartPostShipments [], calculating the total number of elements in the array using the .length property is straightforward. However, I also need to calculate the sum of each field ...

Utilizing the MEAN stack to establish a connection with a simulated data collection

Currently, I am diving into the world of M.E.A.N stack development. As part of my learning process, I have successfully set up a test page where Angular.js beautifully displays and re-orders data based on search criteria. To challenge myself further, I dec ...

After a period of time, NodeJS abruptly crashes while processing a CSV file

Recently, I've been working on a project that involves converting CSV data into XML. To accomplish this, I have been using the fs.createReadStream() method to read the CSV file. However, I encountered an issue where the terminal crashes unexpectedly a ...

Having trouble deciding between JSON, XML, or using a database?

As I work on developing an app that involves sending an id and receiving a JSON node from PHP, I am considering the best approach for storing my data. Should I keep it as a static PHP array as shown in the code below, or should I save the data to an exte ...

How to identify a request timeout when using $http in Angular?

I have a question about how to manage timeouts when making an http request using Angular. Here is the code snippet: $http({ url: url, params: params, method:'POST', headers: { 'Content-Type': 'application/x ...

Activate automatic click or force trigger JavaScript function

In the MVC view I am working with, there is a form that allows for file submission. //Submit file <% using (Html.BeginForm("MethodName","ControllerName", FormMethod.Post, new { enctype = "multipart/form-data"})) { %> <input type=" ...

Display scrollable content at the bottom

I am currently working on creating a chat application using JavaScript (AngularJS without jQuery) and I am wondering if it is possible to have a scrollable div load to the bottom automatically. While I am familiar with the scrollTo JS property, I do not f ...

What is the process for developing an interface adapter using TypeScript?

I need to update the client JSON with my own JSON data Client JSON: interface Cols { displayName: string; } { cols:[ { displayName: 'abc'; } ] } My JSON: interface Cols { label: string; } { cols:[ { label:&a ...

Customizing the Zoom Control Style in Vue Leaflet

I'm currently working on developing a Map App in Dark Mode using Vue, but I've encountered an issue with changing the style of the Zoom Control. Here's what I have tried so far: template> <div class="main-map"> <l ...

Error encountered: `npm ERR! code E503`

While attempting to execute npm install on my project, which was cloned from my GitHub repository, I encountered the following error: npm ERR! code E503 npm ERR! 503 Maximum threads for service reached: fs-extra@https://registry.npmjs.org/fs-extra/-/fs-ex ...

Adding negative values to the Tailwind CSS utility plugin is a simple process that can greatly enhance

Adding Negative Values to Tailwind CSS Utility Plugin Quick Summary: I've developed a custom Tailwind utility plugin that includes numeric values. I'm looking for a way to introduce negative numbers by adding a - at the start of the class, simi ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

Develop a form containing a date input in a special character-free format, along with a validation feature

I am looking to design a form that necessitates users to input a date in the following format: "ddmmyyyy". No slashes, dots, or any other special characters should be included. Only entries matching this specific format will be accepted as valid, any other ...

The compatibility between Node JS and Vue JS front-end seems to be glitchy and

I am currently developing a Node JS backend application and Vue JS front-end. In order to authenticate users, I need to implement sessions in the API. For my backend server, I am using the following components: express (4.18.2) express-session (1.17.3) c ...

Using ES6, when utilizing array map in ReactJS, the function does not produce a return value

One challenge I'm facing involves mapping an array to find a specific string value. Unfortunately, despite my efforts, the map function is not returning anything as expected. class Application extends React.Component { constructor(){ super(); ...

Develop interactive applications with React Native by generating N animated values

Currently, I am in the process of developing a component known as a "Color Palette," which includes a prop called "paletteColors." The "paletteColors" prop is an array with varying lengths that houses color values represented as strings. Within this comp ...

Download files from Firebase storage to a user's device

I have a variety of files such as images, videos, and audio stored in my firebase storage. My goal is to provide users with the ability to download these files to their computers by clicking on a download button. After reviewing the firebase documentation ...