Ionic 2 typescript filer an array

I have an array with below structure :

  • id
  • date
  • start_time
  • end_time

I would like to filter the array to a new array when date is equal to a particle date, e.g. 1996-03-29

May I know how to write in typescript?

console.log(this.existingtimeSlotList); //Array showing correctly [object, object, object …]

// filter the this.existingtimeSlotList when the date is equal to 1996-03-29, and save to this.newtimeSlotList (may i know how to achieve it?)

console.log(this.newtimeSlotList);

Many thanks !

Hi @eheading,

You can use array.filter() method,

let input = '1996-03-29';
let newtimeSlotList = this.existingtimeSlotList.filter((t) => t.date == input);

I suggest you to use moment.js for comparison for the date, like

 this.existingtimeSlotList.filter((t) => moment(t.date).isSame(moment(input)));
1 Like

HI @itsmemyk

Many thanks for your suggest, I have used this method, but the outcome of newtimeSlotList is a null array.
May I know is it because this filter method only suit for single array of single item?
My case should be array of object and should use other methods ?
Thanks.

Hey @eheading,

you can quickly try this example

let list = [
  { id: 1, date: '2016-09-16' },  
  { id: 2, date: '2016-09-14' },
  { id: 3, date: '2016-09-12' },
  { id: 4, date: '2016-09-16' },
];

let newList = list.filter((t) => t.date == '2016-09-11');
console.log(newList);
2 Likes

Hey @itsmemyk,

Many thanks, it works ! You saved my life :grin:

1 Like

That’s what i need! :heart_eyes: