Transferring data between arrays in TypeScript depending on a specified condition

I am looking to transfer all data from one array to another in TypeScript based on a certain condition.

array: any =
            [
                {
                    Hostname: 'CBA',
                    Certificate_Expiry_Date: 'Thu Mar 25 16:32:48 GMT 2021',
                    '': ''
                },
                {
                    Hostname: 'CBCB',
                    Certificate_Expiry_Date: 'Wed Apr 07 11:19:01 IST 2021',
                    '': ''
                },
                {
                    Hostname: 'cbcb',
                    Certificate_Expiry_Date: 'Thu Apr 01 12:05:22 IST 2021',
                    '': ''
                },
                {
                    Hostname: 'cbm',
                    Certificate_Expiry_Date: 'Sat Apr 04 10:45:19 IST 2020',

            ];

        
        alert() {
            if (this.array.Certificate_Expiry_Date > Date) {
                this.array.forEach(item => {
                    this.alertsArray.push(
                        item.Hostname,
                        item.Certificate_Expiry_Date
                    );
                  });
               }
            console.log(this.alertsArray);
          }

I need help modifying the above code to add an object to the alerts array when the certificate expiration date is less than two months away, as my current implementation does not seem to be working as expected. Any assistance would be greatly appreciated.

Answer №1

Looks like you're attempting to access an undefined value in the array using dot notation, which is not supported for arrays

  alert() {
    if (this.array.Certificate_Expiry_Date > Date) { <--- dot notation on the array wont work
      this.array.forEach(item => {
        this.alertsArray.push(
           item.Hostname,
           item.Certificate_Expiry_Date
        );
      });
    }
    console.log(this.alertsArray);
  }

Try iterating through the array and checking if your dates are less than 60 days apart. If they are, push that item into your alerts array

To check your condition, convert the expiration date and today's date to new Date() objects, then calculate the difference in milliseconds and divide by the number of milliseconds in a day. Check if this is less than 60 days.

You might need to adjust the calculations here to make it work

 alert() {
    const milsInDay = (1000*60*60*24);
    const today = new Date().getTime() / milsInDay;
    this.array.forEach((item) => {
       const exp = new Date(item.Certificate_Expiry_Date).getTime() / milsInDay;
       if(exp - today < 60) {
          this.alertsArray.push(item);
       }
    });
    console.log(this.alertsArray);
 }

Answer №2

To form a fresh array containing only elements that meet a particular condition, employ the filter() method and expand (...) to add those elements into your designated target array:

this.targetArray.push(...this.mainArray.filter(item => item.Expiry_Date > Current_Date));

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

Identifying when the mouse cursor changes on a website

Is there a way to detect when the mouse cursor changes as it hovers over different page elements? An event similar to this would be ideal: window.onmousecursorchange = function(e) { // e would provide information about the cursor // for example, ...

There appears to be an issue with the dynamic functionality of RouterLink in Angular 6

user-dashboard.html <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link" routerLink='/dashboard'>User Dashboard</a> </li> <li class="nav-item" *ngFor="let cat of categories; let i = in ...

Unexpected issue with sliding menu toggle implementation

I have been struggling to make a menu slide to the left when a button is clicked, and then slide back to its original position when the same button is clicked again. Although I have been using the toggle method, it doesn't seem to be working for me. I ...

Steps to make a dropdown menu that showcases all files within a folder using HTML5 and Javascript

I am attempting to implement a dropdown menu that displays all the files currently in a directory. The goal is for the user to be able to click on a file in the list and have the name of that file printed to the console. Here is my current progress: HTML ...

Transform an unidentified function into a new type using TypeScript

Consider the following code snippet: type T = (x: number) => boolean; let fn = function(a: string, b: boolean, c: T){}; fn('yes', true, ()=> { }); Unfortunately, this code will not compile. The goal is to cast the anonymous function to ...

The catch-all route handler is triggered following a response being sent by a designated route handler

Currently, I am facing a peculiar issue with the routing on my Express-based server while trying to implement authentication. Here's a snippet of code that highlights the problem: app.get('/', function (req, res) { console.log('thi ...

Transform HTML elements within an *ngFor iteration based on a specific variable in Angular 4

In my current project using Angular 4, I am faced with the task of dynamically modifying HTML tags within an *ngFor loop based on a variable. Here is the code snippet that represents my approach: <mat-card-content *ngFor="let question of questionGrou ...

What is the best way to extract subscribed data from a function in Angular 2?

I'm currently working on a function that makes multiple API calls using for loops. My goal is to combine all the responses and return them once the last API call's data is received. Although I can successfully combine the data within the functio ...

Angular: Retrieving the Time Format from the Browser

Is there a way to retrieve the time format from the operating system or browser within Angular in order to display time in the user's preferred format? I have attempted to search for a solution, but have come up empty-handed. Thank you in advance! ...

Ensuring Consistency in Array Lengths of Two Props in a Functional Component using TypeScript

Is there a way to ensure that two separate arrays passed as props to a functional component in React have the same length using TypeScript, triggering an error if they do not match? For instance, when utilizing this component within other components, it sh ...

"Unable to access data from 'POST' form using node.js results in 'undefined'

My task involves sending input data from an HTML page to my localhost server. In the HTML, I am using a "form" like this: <form action="/log-in", method="POST"> <h3 style='font-family: Antic Slab; font-size: 23px;'>Log in to ...

Video playback in IE8 is not supported by mediaelement.js

I have gone through all the questions posted here, but none of them have solved my issue. Currently, the video loads and plays in Chrome, Safari, FF, and IE9, but not in IE8, which is the browser I need to support. You can see the page here. Despite tryi ...

Guide on creating a dash-patterned line over a rectangle using PixiJS and Angular

https://i.sstatic.net/uIksi.jpg In this example, we are creating a PixiJS application that draws a solid-stroked rectangle. Unfortunately, PIXI.Graphics does not have a built-in feature to draw dashed strokes. import { Component, OnInit } from &ap ...

Utilize $http.get within a service/factory to retrieve a set of items

I am trying to utilize a http.get promise within an angularjs service, perform some manipulation on the retrieved collection, and then pass it back to a controller... My query is regarding the proper usage of $http.get() in a service to fetch and modify t ...

Issue encountered when attempting to utilize multiple datasets with Twitter Typeahead/Bloodhound

Hello, I am currently learning how to use Typeahead and Bloodhound with the latest javascript. Below is a snippet of my code: Html: <div id="multiple-datasets"> <input class="typeahead" type="text" placeholder="NBA and NHL teams"> </div ...

Encountering an error with dynamic routing in Angular 4 when using dynamic components

Upon receiving routing configuration from a server and loading it before the application bootstrap, the config.json file contains the following setup: [{ "path": "dashboard", "component": "SingleComponent", "data": {...} }, { "path": "payment", ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

The showdown between unloading and Java Script - onbeforeunload begins now

Looking for a way to detect when a user exits my website. I have come across discussions about using AJAX calls to simulate pings for this purpose. I have found documentation on the unload event that occurs before the browser window closes or redirects. ...

What could be the reason for the malfunction of the loadingItem in PrimeNG's VirtualScroller

Currently, I have integrated PrimeNG 11.0.0-rc.2 with Angular 11 and am utilizing the VirtualScroller Component. However, I've encountered an issue where the loadingItem ng-template, designed to display a loader statement, is not functioning correctly ...

Get rid of the arrow that is displayed when using the `time` input type in HTML5

Recently, I encountered an issue with the default HTML5 code snippet. My custom background looked perfect except for a pesky black arrow appearing on the right side. In this image, you can see the problematic black arrow that needs to be removed. I attemp ...