firebase -> date order reverse

The Firebase Database will always return results in ascending order. There is no way to reverse them.

There are two common workaround for this:

  1. Let the database do the filtering, but then reverse the results client-side.
  2. Add an inverted value to the database, and use that for querying.

These options have been covered quite a few times before. So instead of repeating, I'll give a list of previous answers:

  • Display posts in descending posted order
  • Sort firebase data in descending order using negative timestamp
  • firebase sort reverse order
  • Is it possible to reverse a Firebase list?
  • many more from this list: https://www.google.com/search?q=site:stackoverflow.com+firebase+reverse%20sort%20javascript

This is how I solved it: First I made a query in my service where I filter by date in milliseconds:

 getImages (): Observable<Image[]> {
this.imageCollection = this.asf.collection<Image>('/images', ref => ref.orderBy('time').startAt(1528445969388).endAt(9999999999999));
this.images = this.imageCollection.snapshotChanges().pipe(
  map(actions => actions.map(a => {
    const data = a.payload.doc.data() as Image;
    const id = a.payload.doc.id;
    return { id, ...data };
  }))
);
return this.images;

}

Then to get the newest date first I added this to my component where I call the method from my service:

let date = new Date;
let time = 9999999999999 - date.getTime();
console.log(time);

I pass the time let as the date. Since a newer date will be a bigger number to deduct from the 9999999999999, the newest date will turn up first in my query inside my service.

Hope this solved it for you


You can simply make a function to reverse the object and then traversing it.

function reverseObject(object) {
    var newObject = {};
    var keys = [];

    for (var key in object) {
        keys.push(key);
    }

    for (var i = keys.length - 1; i >= 0; i--) {
        var value = object[keys[i]];
        newObject[keys[i]]= value;
    }       

    return newObject;
}