user3642173
user3642173

Reputation: 1255

Sort data descending list Firebase Angular2

Is it possible to sort values descending using Firebase in Angular2? In my example I want to use the timestamp field as the sort value.

I have tried with this approach but haven't been succesfull in sorting it descending.

this.items = af.database.list('/items', {
      query: {
        orderByChild: 'timestamp'
      }
    });

One option I can think of would be pushing these values to a new array as they arrive and then return that array but that seems suboptimal.

Upvotes: 1

Views: 1458

Answers (1)

wickdninja
wickdninja

Reputation: 1039

I'm not familiar with Firebase queries, but if receiving the data already sorted isn't a strict requirement you could simply sort the data after receiving it.

//using ES 2016 syntax (copy and paste in latest Chrome dev tools to try out)

var times = [new Date('1/1/16').toISOString(),new Date('1/2/16').toISOString(),new Date('1/3/16').toISOString()];

console.log(times);
// ["2016-01-01T05:00:00.000Z", "2016-01-02T05:00:00.000Z", "2016-01-03T05:00:00.000Z"]

var sortedDesc = times.sort((t1,t2) => {
    if(t1 === t2) return 0;
    if(t1 > t2) return -1;
    if(t1 < t2) return 1;
});

console.log(sortedDesc);
// ["2016-01-03T05:00:00.000Z", "2016-01-02T05:00:00.000Z", "2016-01-01T05:00:00.000Z"]

Upvotes: 1

Related Questions