Viktor Molnar
Viktor Molnar

Reputation: 99

Sorting array by date and time in same time?

I am building shedule app, so i need to sort items by date and time in same time. Like you see in example i can only filter hours and minuts and that works, but i need to filter dates too

I am storing date in datebase like YYYY-MM-DD and time by hours and minuts like string for example: hours:"08",minuts:"25".

 this.ord3ref.on("child_added", data => {
      this.ord3.push({
        key: data.key,
        data: data.val()
      });
      this.ord3.sort(
        (a, b) => a.data.hours- b.data.hours || a.data.minuts- b.data.minuts
      );
    });

enter image description here like you see on image it sorts array by hours and minuts, but its need to be sorted by dates first, that with hours and minuts

like you see on image it sorts array by hours and minuts, but its need to be sorted by dates first, than with hours and minuts...

Upvotes: 0

Views: 430

Answers (1)

Quizzy
Quizzy

Reputation: 46

If the data contains a key/value for date then you should be able to just substitute your sort function with this:

this.ord3.sort(
    (a, b) => {
        var dateA = new Date(a.data.date).valueOf();
        var dateB = new Date(b.data.date).valueOf();
        return a.data.hours - b.data.hours || a.data.minuts - b.data.minuts || dateA - dateB;
    }
);

javascript Date objects can be created from the date strings in the format YYYY-MM-DD.

The .valueOf() method returns the number of milliseconds from UTC time - see MDN's explanation of it.

Upvotes: 1

Related Questions