Spinteractive
Spinteractive

Reputation: 261

Why can't I sort a date array returned by my firebase query?

I have a sort function that works on a hard coded date array. But when I try to sort on a date array created by my firebase query, I am unable to sort.

//THIS DOES NOT SORT
const dayRef = firebase.database().ref('Calendar/District/' + district + '/validDays/');
dayRef.once('value').then(function (snapshot) {
    var value = snapshot.val();
    if (value) {
        snapshot.forEach(function (childSnapshot) {
            var myDate = childSnapshot.val();
            days.push(new Date(myDate.date)); //ARRAY DOES NOT SORT
        });
    }
});

// THIS SORTS MY HARD CODED ARRAY
var dates = [
    new Date(2010, 5, 10),
    new Date(2010, 2, 10),
    new Date(2010, 3, 10),
    new Date(2010, 8, 10),
    new Date(2010, 1, 10),
    new Date(2010, 6, 10),
    new Date(2010, 11, 10),
    new Date(2010, 8, 10)];

var date_sort_asc = function (date1, date2) {
    if (date1 > date2) return 1;
    if (date1 < date2) return -1;
    return 0;
};

console.log(dates.sort(date_sort_asc)) // this sorts
console.log(days.sort(date_sort_asc)) // this does not sort
</script>

I need to sort the days array in ascending order

Upvotes: 2

Views: 114

Answers (3)

Spinteractive
Spinteractive

Reputation: 261

Thank you Jonathon Hamel - this is the answer... Sort after your snapshot.forEach since you use asynchronous code.

Upvotes: 0

Jonathan Hamel
Jonathan Hamel

Reputation: 1393

Your code for firebase is asynchronous. You should sort in the .then block, after your foreach loop. Check this fiddle

snapshot.forEach(function (childSnapshot) {
    var myDate = childSnapshot.val();
    days.push(new Date(myDate.date));
 });
 days.sort(date_sort_asc); // Sort here
 console.log(days);

Upvotes: 1

Drewness
Drewness

Reputation: 5072

You are sorting before the promise is resolved.

if (value) {
    snapshot.forEach(function (childSnapshot) {
        var myDate = childSnapshot.val();
        days.push(new Date(myDate.date)); //ARRAY DOES NOT SORT, yet...
    });
    days.sort(date_sort_asc); // <-- Do it here
}

Upvotes: 2

Related Questions