Filter an array of dates that fall within a specified range of two dates

I have a list of dates and I'm attempting to filter out dates that fall outside of a specific date range. However, I'm encountering an issue where some dates before the "from" date are still present in the filtered list. What could be causing this problem?

$scope.filterUpcomingEvents = function() {

    $scope.arrayOfEventData = JSON.parse(JSON.stringify($scope.tempArray));

    console.log($scope.tempArray, "arrayofeve");
    
    for (let d = 0; d < $scope.arrayOfEventData.length; d++) {
        debugger;
        console.log(d);
        console.log(new Date($scope.tempArray[d].event_date), "from", $scope.upcomingEventFrom);
        console.log(new Date($scope.tempArray[d].event_date) < $scope.upcomingEventFrom);
        console.log(new Date($scope.tempArray[d].event_date), "to", $scope.upcomingEventTo);
        console.log(new Date($scope.tempArray[d].event_date) > $scope.upcomingEventTo);
        console.log("---");
        
        if (new Date($scope.arrayOfEventData[d].event_date) < $scope.upcomingEventFrom || new Date($scope.arrayOfEventData[d].event_date) > $scope.upcomingEventTo) {
            $scope.arrayOfEventData.splice(d, 1);
        }
    }
    
    console.log($scope.arrayOfEventData, "after splice");
}

Despite receiving true results for some comparisons in the console, the specified values are not being removed when checking the final array afterwards.

List of dates:

0: {
        event_id: "49",
        event_name: "julyevent",
        event_date: "2018-07-13",
        event_time: "11:00AM",
        event_type_id: "2",
        …
    }
1: {
        event_id: "50",
        event_name: "up event1",
        event_date: "2018-06-22",
        event_time: "11:11AM",
        event_type_id: "2",
        …
    }
2: {
        event_id: "52",
        event_name: "twe",
        event_date: "2018-06-29",
        event_time: "11:11AM",
        event_type_id: "2",
        …
    }
3: {
        event_id: "55",
        event_name: "eve4",
        event_date: "2018-06-23",
        event_time: "10:22PM",
        event_type_id: "2",
        …
    }
4: {
        event_id: "56",
        event_name: "eve5",
        event_date: "2018-06-25",
        event_time: "11:11AM",
        event_type_id: "2",
        …
    }
5: {
        event_id: "57",
        event_name: "eve6",
        event_date: "2018-06-28",
        event_time: "10:00AM",
        event_type_id: "2",
        …
    }
6: {
        event_id: "58",
        event_name: "eve7",
        event_date: "2018-06-28",
        event_time: "9:00AM",
        event_type_id: "2",
        …
    }
7: {
        event_id: "59",
        event_name: "eve8",
        event_date: "2018-07-12",
        event_time: "7:00AM",
        event_type_id: "2",
        …
    }
8: {
        event_id: "60",
        event_name: "eve9",
        event_date: "2018-06-19",
        event_time: "4:00AM",
        event_type_id: "2",
        …
    }
9: {
        event_id: "61",
        event_name: "eve10",
        event_date: "2018-06-20",
        event_time: "8:00PM",
        event_type_id: "2",
        …
    }
10: {
        event_id: "62",
        event_name: "eve11",
        event_date: "2018-06-23",
        event_time: "3:00AM",
        event_type_id: "2",
        …
    }
11: {
        event_id: "63",
        event_name: "eve12",
        event_date: "2018-06-21",
        event_time: "10:22PM",
        event_type_id: "2",
        …
    }
12: {
        event_id: "64",
        event_name: "eve13",
        event_date: "2018-06-24",
        event_time: "6:00AM",
        event_type_id: "2",
        …
    }

Answer №1

Splicing from the same array while incrementally looping can cause modifications to the array and shift items, potentially causing missed iterations.

To avoid this issue, consider using a backward loop with a while loop to iterate through the array without affecting the splicing direction.

let index = $scope.arrayOfEventData.length;
while(index--){
  // your code here
}

Answer №2

To achieve this functionality, you can utilize the Array.filter method:

 $scope.arrayOfEventData =  $scope.arrayOfEventData.filter((item) => (new Date(item.event_date) >= $scope.upcomingEventFrom || new Date(item.event_date) <= $scope.upcomingEventTo)));

Answer №3

The issue arises from incrementing d even after removing an element in the loop with d++. To address this problem, simply remove d++ from the loop as shown below:

for (let d=0; d<...;      ) // no d++
...
  if ()
    splice(d, 0);
  else
    d++;

An alternative approach to avoid such complications is by using Array.filter method.

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

What is the process to activate a resize event with nvd3?

I am trying to figure out how to make the resize event trigger on nvd3 for AngularJS. The issue I am facing is that when I add line breaks in the labels of the pie chart and then resize the window, the labels revert back to a single line. What I want is ...

Executing JavaScript code within a Django application to load a file

Utilizing a JavaScript tool called jQuery FileTree within my Django application has presented a dilemma. This particular JavaScript requires access to a python script path, but incorporating Django template tags directly into JavaScript poses an issue. Wi ...

Step-by-step guide to creating a perforated container:

I'm putting together a step-by-step guide on how to navigate through my app for the first time. Imagine a pop-up that explains how to use a specific button During the tutorial, I envision a darkened background with a highlighted circle around the bu ...

How can I connect a click event on one div to trigger another using jquery?

Could someone assist me with the proper terminology? I am interested in clicking one div, which would then automatically trigger the click on another div. For example, if I click on div 1, I want div 2 to be clicked by JavaScript without user interaction ...

Utilizing Jquery select2 to enhance user experience by organizing JSON data with optgroup and

Currently, I am working with select2 in conjunction with spring mvc. The data I need to display is retrieved from my controller and should be displayed as options. However, I would like these options to be grouped within optgroups while also incorporating ...

Find a way to sift through an array of objects to ensure that each object is distinct from the others

Here is an array where objects with the same values for st and ct should be considered identical. For example, the first and third objects have the same values for st and ct, so the third object should be filtered out of the final array. How can I achiev ...

Show the res.send() method from express.js without replacing the existing html content

Currently, I am in the process of developing a calculator application using express.js. The app needs to handle get requests for an HTML file and post requests that capture user input and provide the response accurately. My challenge lies in showcasing the ...

What is the best way to exclude React.js source files from a fresh Nest.js setup?

My setup includes a fresh Nest.js installation and a directory named "client" with a clean create-react-app installation inside. Here is the project structure: ./ ...some Nest.js folders... client <- React.js resides here ...some more Nest.js fo ...

Commit to persevering until you achieve success

I'm currently working with native node.js Promises and did not find any useful information in this thread. Essentially, I am dealing with a function that looks like this: var foo = foo (resolve, reject) { return obj .doA() .doB() ...

Switch out the icons within a return statement in JavaScript

Help! I have 5 empty star icons (<StarBorderIcon/>) displayed for a product on the material-ui website. I need to replace them with filled star icons (<StarIcon/>) based on the rating entered into a function. I attempted to use replace(), but i ...

Utilizing directive scope variables to generate dynamic templates

Looking for a solution to dynamically render forms with various controls based on a specific Type value specified in a JSON object. The form will be created based on user input, so the necessary question types may vary. While we will define the types, they ...

What is the best way to convert API data into a currency format?

Hello, I need assistance with formatting data retrieved from an API into a currency format. The code below successfully retrieves the data but lacks formatting. For instance, if the data displays as 100000000, I would like it to be formatted as IDR100.000. ...

Tips for successfully sending a string containing special characters to a server-side function

I am facing an issue with my basic app service that generates a title. The problem arises when special characters are passed from the client-side page to the server-side function, resulting in question marks being displayed. Is there a way to resolve this ...

ObservableResolve(): Unleashing the power of RxJS5 for handling asynchronous data streams

Hey there! To dive deeper into RxJS, I thought of creating my own custom Rx operator. So here's a straightforward one that seems to be working smoothly: Rx.Observable.prototype.multiply = function (input) { const source = this; return Rx.O ...

Viewing HTML web pages using Mozilla Firebox

Printing an HTML table with lots of content has been a challenge for me. Google Chrome didn't work, so I switched to Mozilla Firefox. However, now Firefox is breaking the page inside the table. My question is how can I trigger print preview in Firefox ...

Unable to view AngularJS expression output

I'm struggling to make an AngularJS expression appear on the screen. The content inside the curly braces is not displaying, even though I have checked the app with ng-inspector and confirmed that an object is being created using the ng-model directive ...

How can you exhibit various images without relying on the <img> tag?

Is there a more efficient way to display over 500 images from a folder on an HTML page without the need to manually write out each img src tag? I have searched online for solutions, but most suggestions involve using PHP or "glob", which I am hesitant to ...

What steps can be taken to restrict access to the next page for users who are not logged in?

In my main JavaScript file, I am trying to implement a condition where users must be logged in to access the welcome page. If a user is not logged in, they should be redirected to the login page by default. However, in my current code, the form is submitti ...

Using jQuery to include Chinese characters in a request header

When making a jQuery post request, I need to set client information in the header. This is how my call looks: jQuery.ajax({ url : myURL, type : "POST", beforeSend : function(request){ request.setRequestHeader('someInfo', clie ...

"Error in react-three-fiber: Only the last mesh retains its model, all others are

Currently, I am working on a React application where I am using react-three-fiber to visualize data in a 3D environment. My goal is to create various models by passing data representing their characteristics as props into components. However, I am encounte ...