ALL
ALL

Reputation: 101

Sort array based on string transformed into date

So I have an array containing reviews (which I retrieve from firebase firestore). The field 'date' is string in firestore. How can I sort the reviews in descending order based on this date? I have tried this but they are in the retrieval order.

const getReviews=async()=>{
        let reviewsClone=[];
        const q = query(collection(db, "reviews"), where("product", "==", uniqueProductName.product));
        const querySnapshot=await getDocs(q);
        querySnapshot.forEach((doc)=>{
            reviewsClone.push(doc.id);
        })

        reviewsClone.sort(function(a,b){
            return new Date(a.date) - new Date(b.date);
          });
        setReviews(reviewsClone);

    }

Upvotes: 1

Views: 175

Answers (2)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

Assuming that all the data is valid, and contains the date key. Your sort function is incorrect. To sort in descending order, your sort function should look like this:

reviewsClone.sort(function(a,b){
        return new Date(b.date) - new Date(a.date);
      });

This documentation should be helpful.

Upvotes: 0

Igor Loskutov
Igor Loskutov

Reputation: 2325

Could you try this? It's likely that you are sorting an array of strings reviewsClone currently, which all have .date prop undefined, therefore .sort has no effect.

const getReviews=async()=>{
        let reviewsClone=[];
        const q = query(collection(db, "reviews"), where("product", "==", uniqueProductName.product));
        const querySnapshot=await getDocs(q);
        querySnapshot.forEach((doc)=>{
            reviewsClone.push(doc);
        })

        reviewsClone.sort(function(a,b){
            return new Date(a.date) - new Date(b.date);
          });
        setReviews(reviewsClone.map(c => c.id));

    }

Upvotes: 1

Related Questions