Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to keep objects with an old date out of my array

I loop through an array of objects that all have a date property. The conditional I set inside the loop to compare the object's date to today's date should take care of just a few of the objects in the array I want kept out because of an old date, however, this conditional is removing all objects in the array for some reason.

It does not work to use getTime(). getTime removes everything from the array. Like I tried here:

constructor (   public navCtrl: NavController,
                                public modalCtrl: ModalController,
                                public loading: LoadingController,
                                public popoverCtrl: PopoverController,
                                public getPostSrvc: getPostsService) {

        this.listOfEvents = [];

        let that = this;

function getPostsSuccess (listOfEventsObject) {

                    for (var i in listOfEventsObject) {

                        if(listOfEventsObject[i].date.getTime() < Date.now()){

                                 that.listOfEvents.push(listOfEventsObject[i]);

                              }//close if
                   }//close for loop
    }//close function
}//close constructor

UPDATE My solution:

export class Home {

    listOfEvents: Array<any> = []; 
    parseDate: number;
    today : number;

    constructor (   //constructor stuff ){

        for (var i in listOfEventsObject) {

            that.today = Date.now();


              that.parseDate = Date.parse(listOfEventsObject[i].date);

                 if( that.parseDate > that.today){

                        that.listOfEvents.push(listOfEventsObject[i]);

                     }//close if  


                }//close for
}//close constructor  
}//close export 
like image 615
Spilot Avatar asked Nov 07 '22 20:11

Spilot


1 Answers

If, as mentioned by RobG in a comment, the value of listOfEventsObject[i].date is a string, you can parse it first, and compare the resulting Date value to Date.now():

if (Date.parse(listOfEventsObject[i].date) < Date.now()) { 
    ... 
}
like image 61
ConnorsFan Avatar answered Nov 14 '22 21:11

ConnorsFan