1

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.

1

1 Answer 1

1

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.