Attempting to eliminate any dates that have already occurred

I am faced with an array containing various dates in string format such as "2016-08-12". My goal is to eliminate any dates that have already passed by comparing them to today's date. I am using TypeScript for this task.

Here is a snippet of my datoArray:

["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10"]

and so on...

Below is the logic I am attempting to apply:

for(var i = 0; i < this.datoArray.length; i++){
    this.skoleAar = parseInt(this.datoArray[i].slice(0,4))
    this.skoleMaaned = parseInt(this.datoArray[i].slice(5,8))
    this.skoleDag = parseInt(this.datoArray[i].slice(8,10))

        if(this.skoleAar < currentYear){
            this.datoArray.splice(i, 1);
        }
        if(this.skoleAar == currentYear && this.skoleMaaned < currentMonth){
            this.datoArray.splice(i, 1);
        }
        if(this.skoleAar == currentYear && this.skoleMaaned == currentMonth && this.skoleDag < currentDay){
            this.datoArray.splice(i, 1);
        }
    }

The variables, `currentYear`, `currentMonth`, and `currentDay` are obtained from another function. When logged, they show integer values like 2016 for the year and 8 for the month when extracted from the start of the array. For `currentYear`, `currentMonth`, and `currentDay`, it displays 2016, 11, 20 respectively, representing today's year, month, and day all as integers. However, despite these comparisons of integer values, the conditions inside the "if" statements do not seem to work as expected. It appears there may be an issue with the way I am performing the comparisons. As far as I understand, this should be the correct way to compare integer values, so I am puzzled as to why the logic is failing?

Answer №1

To filter dates in ISO-8601 format, you can utilize the Date.parse() method.

var dates = ["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10", "2016-12-15"];

function excludePreviousDates(data) {
  var today = new Date();
  console.log('Initial state: ' + data);
  var updated = dates.filter(function(dateString) {
    return Date.parse(dateString) >= today;
  });
  console.log('Final state: ' + updated);
  return updated;
}

var filteredDates = excludePreviousDates(dates);

Answer №2

It appears that your date values are in compliance with RFC standards, which means they can be directly used in a new Date object. To filter these dates based on their relation to the current date, you can compare them to today:

var today = new Date()
var futureDates = this.datoArray.filter(d => new Date(d) >= today)

(for pre-ECMA6:)

var today = new Date()
var futureDates = this.datoArray.filter(function (d) {
  return new Date(d) >= today;
})

Answer №3

In my opinion, the issue does not seem to be related to the dates.

It appears that the problem arises when trying to delete items from the array while simultaneously iterating through the same array.

One possible solution could be to iterate through the array in reverse order or keep track of the indexes that need to be removed before actually deleting them. It's important to remember that removing an item will shift the index of all remaining items - starting with the highest index might help avoid confusion.

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

Difficulty loading AngularJS 1.3 page on Internet Explorer 8

Being an avid user of Angular, it pains me to even bring up the topic of IE8, a browser that many consider to be pure evil and deserving of extinction. Despite my reservations, I am experiencing difficulties with loading Angular 1.3 in IE8. The page break ...

Unable to Toggle Bootstrap 5 Dropdown

Take a look at my code below. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewpor ...

Top recommendations for implementing private/authentication routes in NextJS 13

When working with routes affected by a user's authentication status in NextJS 13, what is the most effective approach? I have two specific scenarios that I'm unsure about implementing: What is the best method for redirecting an unauthenticated ...

How to Retrieve the Absolute Index of the Parent Column Using jQuery Datatables

I recently developed a custom column filtering plugin for datatables, but I've encountered a minor issue. Within each column footer, I have added text inputs, and now I am trying to capture their indexes on keyup event to use them for filtering. In ...

send array to the sort function

How can I sort a data array that is returned from a function, rather than using a predefined const like in the example below: const DEFAULT_COMPETITORS = [ 'Seamless/Grubhub', 'test']; DEFAULT_COMPETITORS.sort(function (a, b) { re ...

Verify if the JSON attribute is empty

My input contains the following: { "headers": { ... }, "body": { "RequestInfo": { ... , "Identificator": null } } <filter regex="false" source="boolean($ctx:Identificator)"> - check if it exists (even when it's ...

Deciphering a JSON array by value or key

I have a JSON array that I need to parse in order to display the available locations neatly in a list format. However, I am struggling with where to start. The data should be converted to HTML based on the selected date. In addition, a side bar needs to s ...

Updating a model within an ng-repeat directive from external sources

Within my controller, there is a repeater where each item has its own unique status: <div ng-controller="..."> <div ng-repeat"...">{{status}}</div> </div> Currently, changing the status within the repeater by using status = &apo ...

Creating a legitimate svg element using javascript

While working with SVG, I had an issue where I added a <rect> element directly into the svg using html, and then created a new element (without namespace) <circle> with javascript. However, the <circle> element did not display in the svg ...

Creating reducers for a unique data type: A step-by-step guide

Today, I was working on enhancing a shopping website using React Typescript and Context API. My goal is to utilize React Reducers to manage the state of my Shopping Cart. I have custom Types defined for the Product type, which includes an Items Array and s ...

Having trouble rendering Next.JS dynamic pages using router.push()? Find out how to fix routing issues in your

The issue I am facing revolves around the visibility of the navbar component when using route.push(). It appears that the navbar is not showing up on the page, while the rest of the content including the footer is displayed. My goal is to navigate to a dy ...

Progress Bars Installation

For more detailed information, visit: https://github.com/rstacruz/nprogress After linking the provided .js and .css files to my main html file, I am instructed to "Simply call start() and done() to control the progress bar." NProgress.start(); NProgress. ...

Retrieve the initial value of the input element following a modification

Is there a way to retrieve the original default value of an input field after changing it using .val()? In my HTML, I have various text-inputs with classes .large and .medium, each with its own default text value. What I'm trying to achieve is when a ...

The lifecycle of XMLHTTPRequest objects in JavaScript - from creation to destruction

After years of working with traditional compiled object-oriented languages like C++ and .NET programming, I decided to dip my toes into JavaScript for a new project. As I was experimenting with AJAX, I stumbled upon a perplexing aspect related to how objec ...

Extracting JavaScript OnClick button using Selenium

I'm having trouble extracting the email address from the following URL: https://www.iolproperty.co.za/view-property.jsp?PID=2000026825 that is only visible after clicking on the "Show email address" button. However, every time I attempt to click and r ...

Every time I use my NodeJS MySQL Query function, the results I get are never

Working on a new gaming project involving MySQL for multiplayer functionality. Issue arises when requesting specific queries, where the system retrieves incorrect data or results from previous queries. dat("SELECT * FROM server1;"); Misdirected queries r ...

JavaScript code that opens a URL in a new tab with proper formatting

I'm having trouble figuring out how to make my JavaScript open a URL in a new tab. Here is the script: function viewSource(){ var webcache = "http://webcache.googleusercontent.com/search?q=cache:"; var request = "&prmd=ivn&strip=0& ...

Error message pops up in WebStorm when attempting to access the map object in Angular

Within one of the services in my Angular application, I have utilized the map() function to retrieve data from the GitHub API. getUser(username: string) { // Regular Expression used for String Manipulation return this.http.get('https://api.github.com ...

Converting JSON Data to Map Markers on Google Maps

Currently, I am attempting to pass a Json String into my Javascript code in order to create a list of markers on a Google Map. The map code functions properly as I have successfully tested it with a hard coded Json Object. However, now I need to fetch the ...

The IIS URL rewrite is causing issues with the rewriting of CSS and JS files

Struggling with my URL rewrites - every time I set up a rewrite for a page, it ends up affecting the CSS and JS files linked within the webpage, resulting in them not displaying properly. In an attempt to fix this issue, I tried using fully qualified path ...