How can I sort an array of dates without considering the year in the dates

364 Views Asked by At

In angular 4, I am displaying a list of upcoming birthdays in ascending order. However, it is counting a year as well.

I just want to sort it by date and month but not a year.

How can i display it using pipe or pre-sorting data in array.Please see the image

2

There are 2 best solutions below

0
Ashish Ranjan On

I have created a custom pipe in which I am making the year part of the date as a constant for all the dates and then comaparing their times to get the dates in ascending order. Date.getTime() will give milliseconds passed since Jan 1st 1970, (if we have dates before this point then it will be negative). Since the the comapred dates have their year set as "2000", all of them will give getTime() in positive milliseconds.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sortDate'
})
export class SortDatePipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return value.sort((a, b) => {
      let firstDate = new Date(a);
      let secondDate = new Date(b);
      firstDate.setFullYear(2000);
      secondDate.setFullYear(2000);
      if (firstDate.getTime() < secondDate.getTime()) {
        return -1
      }
      return 1
    })
  }

}

https://stackblitz.com/edit/angular-hsdkau?file=src%2Fapp%2Fapp.component.html

1
kinny94 On

I am just gonna extend @xyz answer above and would suggest you to do something like this,

dobDates = [
    '1949-04-06',
    '1963-04-11',
    '1965-04-05',
    '1970-04-12'
  ]

  ngOnInit(){
    this.dobDates.sort((a, b) => {
      let firstDate = new Date(a);
      let secondDate = new Date(b);
      firstDate.setFullYear(2000);
      secondDate.setFullYear(2000);
      if (firstDate.getTime() < secondDate.getTime()) {
        return -1
      }
      return 1
    })
  }

Sorting and filter pipe perform poorly and prevent aggressive minification. Checkout Angular Documentation