Home > Enterprise >  Sort array based on string transformed into date
Sort array based on string transformed into date

Time:05-21

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

    }

Thank you in advance.

CodePudding user response:

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

    }

CodePudding user response:

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.

  • Related