Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one component and the past classes in another. So far, this is what I have achieved. How can I compare the classes and filter them out from the JSON list that I receive on the frontend side?

html

<tbody>
 <tr *ngFor = "let completeData of schedule">
   <td class="trim">{{completeData.date | date}}</td>
   <td class="trim">{{completeData.course}}</td>
   <td class="trim">{{completeData.location}}</td>
   <td class="trim">{{completeData.instructor}}</td>
   <td class="trim"><nb-checkbox [(ngModel)]="completeData.listing"></nb-checkbox></td>  
   <td class="trim">
    <nb-select>
     <nb-option value="2">Edit</nb-option>
     <nb-option value="3">Delete</nb-option>
     <nb-option value="4" (click)="viewDetails()">View</nb-option>
    </nb-select>
   </td>
 </tr>
</tbody>

component.ts file

schedule: ClassSchedule = new ClassSchedule();
ngOnInit() {
this._classService.GetClassData()
.subscribe((result: any) => {
  this.schedule = result;
})
}

interface for schedule

export interface IClassSchedule {
    course: string | undefined;    
    date: string | undefined;
    hour: string | undefined;
    minute: string | undefined;
    timeofday:  string | undefined;
    totalHours: string | undefined;
    //Other fields not added here
}

Answer №1

By using the partition function, you can divide it into two separate observables.

ngOnInit() {
  const currentTimestamp = Date.now();
  const [futureCourses$, pastCourses$] = this._classService.GetClassData()
    .pipe(partition( item => item.timestamp > currentTimestamp ));

  futureCourses$.subscribe((result) => {
    // Here is the upcoming courses
  })

  pastCourses$.subscribe((result) => {
    // Here is the previous courses
  })
}

This code assumes that you are able to access the timestamp for comparison purposes. If not, you can utilize moment library for easier time comparisons.

Answer №2

If you're looking to categorize past and upcoming schedules, you can develop a function specifically for that purpose:

/*
  This function takes an array of items and sorts them into past and upcoming categories
*/
function groupByDate(items: any[]): { past: any[]; upcoming: any[] } {
  const today = Date.now();
  const initial: { past: any[]; upcoming: any[] } = {
    past: [],
    upcoming: []
  };

  return items.reduce((prev, curr) => {
    const itemDate = new Date(curr.date).getTime();
    const isPast = itemDate < today;

    return {
      past: isPast ? [...prev.past, curr] : prev.past,
      upcoming: !isPast ? [...prev.upcoming, curr] : prev.upcoming
    };
  }, initial);

Check out this stackblitz demo for how to implement and utilize this function with observables.

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

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

Validation in Laravel appears to be ineffective when managing schedules

I have a table that contains schedules for each subject. I want to ensure that every schedule is unique and not duplicated. The table includes columns for room, teacher, time, day, and checker who verifies the schedule. It's essential that there are n ...

Can you explain the distinction between Vue's 'v-on' directive and vue.$on method?

If I have two sibling components set up like this: <div id="root2"> <some-component>First</some-component> <some-component>Second</some-component> </div> ... and these components are coded as follows: Vue.comp ...

What is the best way to show input choices once an option has been chosen from the 'select class' dropdown menu?

When it comes to displaying different options based on user selection, the following HTML code is what I've been using: <select class="form-control input-lg" style="text-align:center"> <option value="type">-- Select a Type --</opti ...

Issue with Pebble SDK/SimplyJS failing to recognize the tab character

Currently, I am facing an interesting challenge while attempting to make my Pebble watch recognize the escape sequence character \t when sending data to my watch using SimplyJS. Here is the code snippet I have been working with: simply.scrollable(tr ...

What is the method for invoking an express middleware function that triggers a file download?

Currently, I am delving into Express and experimenting with middleware. My goal is to initiate a file download when accessing the root route while sending out a "Hello World" message. My attempts so far have been: function initiateDownload(req, res, next) ...

Is there a way to turn off _moz_resizing on my browser?

I am currently using the nicEdit editor and have successfully integrated my own custom image resizing script. However, I am facing an issue where the default _moz_resizing feature in Firefox is interfering with my custom script. My goal is to have specifi ...

employing ts as a reference for the pathway

Every time I reference path using "ts" I include the following code snippet: import * as fs from 'fs'; import * as path from 'path'; However, when I try to run node index.ts, an error occurs: import * as path from 'path'; ...

Using an if-else statement in AngularJS

<ng-switch on="MyData.Status"> <p ng-switch-when="2"> <p ng-if="MyData.SomeProp == false"> Message 1 </p> <p ng-if="MyData.SomeProp == true"> Message 2 </p> ...

Avoid losing any entered form information when leaving the page

As I work on creating a datagrid with hundreds of rows, each row features a checkbox that allows users to select items from the grid. I've noticed that users might spend considerable time filtering and searching through the grid, ticking checkboxes a ...

Is it possible to merge several blobs into one zip file using JSzip?

When attempting to download multiple images as a single ZIP file, the result is receiving separate zip files instead. The console log shows that the 'urls[]' array contains different arrays. const fileURLs = window.URL.createObjectURL(result);// ...

What is causing the malfunction in communication between my React app and Express server via fetch requests?

I am currently facing an issue while trying to connect my react js frontend (hosted on localhost for testing purposes, and also on my S3 bucket) to my node.js/express server deployed on an AWS Elastic Beanstalk environment. To resolve a CORS error, I recen ...

I crafted this dropdown menu, but for some reason, the selections aren't registering when clicked. Below is the code I used. Any assistance would be greatly appreciated!

Hi there, I need some help with getting my code to run properly. I've created a dropdown box using HTML and CSS, but it seems like there's an issue with the JavaScript portion as the options are not being selected. I've included a code snipp ...

Issue encountered while attempting to set up react-native project

Whenever I attempt to create a new react-native project using the command: npx react-native init myproject I encounter the following errors: ERESOLVE is overriding peer dependency npm gives me a warning while trying to resolve: [email protected] ...

Can a props be retrieved and passed as an argument to a function?

My goal is to retrieve a prop from MapsStateToProps using react-redux's connect and then pass it to a child component. This prop serves as an argument for a function, which in turn returns something that becomes the state of the child component. Alth ...

Tips on incorporating JavaScript files into Angular applications

Struggling to incorporate a JavaScript function into Angular, I have installed the plugin "npm I global payments-3ds". I copied the JavaScript files from node_modules and attempted to call them in my component. Below is an example: import { ...

"Retrieve the position of a contenteditable element while also considering HTML

I've been exploring a method to generate annotations within HTML text using JavaScript. The approach involves the user clicking on a contenteditable <div> and obtaining the cursor's position based on their click. Subsequently, when insertin ...

Modify FrameColor of Material UI Inputs when Reset button is clicked

When using Angular Material UI in the Registermenu, I am facing an issue where clicking on the reset button deletes the content but leaves the red frames unchanged. Can anyone provide assistance with this problem? Thank you. Screenshot Here is the code f ...

Nonconforming Typescript argument specification

I've been struggling to pass this TypeScript array to a function. Despite trying multiple parameter types in an attempt to get it to compile, none of them have worked so far. Here is the array in question: var driverTally = [ { dr ...

Ways to verify if an email has been viewed through the client-side perspective

How can I determine if an email has been read on the client side using PHP? I need to verify if emails sent by me have been opened by recipients on their end. Additionally, I would like to extract the following details from the client's machine: 1. ...