Spilot
Spilot

Reputation: 1525

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 

Upvotes: 5

Views: 138

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73731

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()) { 
    ... 
}

Upvotes: 1

Matias Alvin
Matias Alvin

Reputation: 132

I can't say for sure since I don't know what kind of data listOfEventsObject[i].date has. But if that data contain timestamps, you can convert it to milliseconds and compare it to Date.now().

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

let me know if this isn't the answer you looking for, cheers.

Upvotes: 0

Related Questions