Yogesh Gadade
Yogesh Gadade

Reputation: 49

How to Sort the following Array Based on Timespan in AngularFire?

{
0
:
{associate_sales: "j72LOAjajLRbKKK0XYfHcCMghdB3", displayName: "Sneh", email: "[email protected]",  timespan: 1, …}
1
:
{displayName: " Sales4", email: "[email protected]",  timespan: 1, uid: "2e5piC6E8eO16qDDaP0qPA0LDRJ3", …}
2
:
{associate_sales: "c8kMXIkXcRgTUInPbdhL5oinbzv2", displayName: " client11", email: "[email protected]", timespan: 12, …}
3
:
{associate_sales: "j72LOAjajLRbKKK0XYfHcCMghdB3", displayName: "Client1", email: "[email protected]", timespan: 1522320931451, …} }

This is the response I fetch in console. how to fetch this result according to timespan asceding or descending order. I am using following method but its not working

 this.databaseObj2.orderByChild('timespan').once('value', (snapshot) => {
// code
});

Please help. Thanx in advance.

Upvotes: 1

Views: 94

Answers (1)

Sarasa Gunawardhana
Sarasa Gunawardhana

Reputation: 1119

First push data into the array as json object.

let temp_array = [];
this.databaseObj2.orderByChild('timespan').once('value', (snapshot) => {
   let result = snapshot.val();
   for(let k in result){
      temp_array.push({
         id : k, // this "K" gives the id of you object
         timespan : result[k].timespan,
         display_name : result[k].displayName,
         //rest of data 
      })
   }
});

temp_array.sort((a, b) => parseFloat(b.timespan) - parseFloat(a.timespan));

Upvotes: 2

Related Questions