Sort records in descending order using Firebase


#1

How do I sort records to orderBy records from the last item added to the first. Descending order.


#2

Anyone has any idea? Been googling around and it seems that firebase does not support ordering in descending order


#3

Indeed, they do not support ordering in descending order.

However what you can do, if you want to order based on a timestamp, is to input a negative timestamp in your database, then order using orderByChild(‘timestamp’) => it works great

If it’s ordering another field, that cannot thave a “-” (minus) sign, then you can use a service.

Here is what I do, ordering in descending order from the ordered firebase data:

ng-repeat="data in arrayOfData | orderObjectBy:'field':true" (with true for “descending order”, see below)

and then the service orderObjectBy:

.filter('orderObjectBy', function() {
  return function(items, field, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      return (a[field] > b[field] ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
})

#4

Thanks for the negative timestamp idea, wonderful!