1

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);

    }
3
  • What is the date format? Any example string? Commented May 21, 2022 at 14:09
  • If the string is in ISO format, you may want to user OrderBy in the firebase query instead. Commented May 21, 2022 at 14:21
  • the string is 'dd/mm/yyyy' Commented May 21, 2022 at 14:24

2 Answers 2

1

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));

    }
Sign up to request clarification or add additional context in comments.

3 Comments

yes, I think you're right. but this still not works
It's not one error but several, then. Probably the answer above mine would help. Also check that new Date(a.date) and new Date(b.date) return correct dates indeed.
ok so I had to change the date format from my db from 'dd/mm/yyyy' to 'mm/dd/yyyy' and it works now (also is b.date - a.date)
0

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.

Comments

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.