Eo1992
Eo1992

Reputation: 11

How to filter an array by date

i want to be able to display my array and be able to filter by date. for example in between "01-02-2017" and "02-02-2017".

ive tried doing this but i dont think im implementing it correctly

export class AppComponent {
  snapshots = [
    { date: '01-02-2017', rooms: 2869, users: 1783, location: 'All' },
    { date: '01-05-2017', rooms: 2769, users: 1655, location: 'All' },
    { date: '03-02-2017', rooms: 2025, users: 1911, location: 'All' },
    { date: '01-02-2017', rooms: 1278, users: 1167, location: 'All' },
    { date: '02-02-2017', rooms: 2028, users: 1940, location: 'All' },
    { date: '01-10-2017', rooms: 2113, users: 2001, location: 'All' },
    { date: '03-02-2017', rooms: 2654, users: 1841, location: 'All' },
    { date: '01-02-2017', rooms: 1264, users: 1140, location: 'All' },
    { date: '01-02-2017', rooms: 2918, users: 2557, location: 'All' },
    { date: '01-20-2017', rooms: 2160, users: 2112, location: 'All' }
  ];
  start;
  end;

   ngOnInit() { 

   }

filter(){
  this.snapshots = this.snapshots.filter(m => {
  if ( m.date > this.start && m.date < this.end)
  return this.snapshots
  })
}
}

Upvotes: 1

Views: 72

Answers (2)

wentjun
wentjun

Reputation: 42526

The safest way will need to convert all of them to JavaScript Date objects. You can't just use getTime() on JavaScript strings. Also, you will have to return 'm' instead of 'this.snapshots'.

filter(){
  this.snapshots = this.snapshots.filter(m => {
    if (new Date(m.date).getTime() > new Date(this.start).getTime() && new Date(m.date).getTime() < new Date(this.end).getTime()) {
     return m;
    }
  })
}

Upvotes: 0

Abel Valdez
Abel Valdez

Reputation: 2408

You need to use getTime() function of Date Class

filter(){
  this.snapshots = this.snapshots.filter(m => (m.date.getTime() > this.start.getTime()) && (m.date.getTime() < this.end.getTime()))
}

Upvotes: 1

Related Questions