Search code examples
javascripthtmlangularsortingangular2-pipe

How to order by closest date to today using Angular2 pipe


Say I have an Event collection:

export class Event {
  startingTime: Date
}

And I want to display them ordered starting from the closest to TODAY, what would that OrderByUpcomingToLatestPipe look like?

<event-element *ngFor="let event of events | orderByUpcomingToLatest"></event-element>

Edit:

I want the array to be arranged in descending order when the date closest to today is the first and the date that is the farthest from today is the last (dates that have already passed will be after the far ordered the same way)


Solution

  • So here's the working pipe

    import {Pipe, PipeTransform} from "@angular/core";
    
    @Pipe({
      name: "upcomingToLatest"
    })
    export class UpcomingToLatestPipe implements PipeTransform{
      transform(array: any, fieldName: any): any {
        if (array) {
          let now: Date = new Date();
    
          array.sort((a: any, b: any) => {
            let date1: Date = new Date(a.object[fieldName]);
            let date2: Date = new Date(b.object[fieldName]);
    
            // If the first date passed
            if(date1 < now){
              // If the second date passed
              if(date2 < now){
                return 0
              } else {
                return 1
              }
            } else {
              // If the second date passed
              if(date2 < now) {
                return -1
              } else if(date1 < date2) {
                return -1
              } else if(date1 > date2) {
                return 1
              } else {
                return 0;
              }
            }
          });
        }
    
        return array;
      }
    }
    

    A quick explanation for that if tree:

    1. If the first date is in the past

      1.1 If the second date is in the past - the order of them does not matter

      1.2 Else, meaning the second is in the future, bring second date higher in the order

    2. Else, meaning the first date is in the future

      2.1 If the second date is in the past, bring first date higher in the order

      2.2 Else if the first date is before the second date, meaning first date is closer to now than the second date, bring first date higher in the order

      2.3 Else, meaning the second date is closer to now than the first date, bring the second date higher in the order