skip to Main Content

I have posts for a group chat stored in an array. I’m trying to get the newest posts to be shown at the top and the oldest at the bottom. I’m not sure what to do or how I could maybe get new posts to be [0] in the array.

Below is the Firestore schema.

enter image description here

2

Answers


  1. You can use post.insert(0,...) (when adding to the list that way it’s easier to sort without any function)

    In the code above post is your List/arry name, then same way you call .add to a List you can call .insert(0,...) where the "0" is your index.

    so what it does is, it inserts every new item to the List at "Index 0" which "0" is the first position in any List, Map or array

    Login or Signup to reply.
  2. I recently answered a similar question, where I provided a recommendation to use arrays for comments that correspond to a particular post. Now, when it comes to sorting, as Doug mentioned in his comment, Firestore doesn’t have that capability. There is no mechanism present that can sort the objects within an array. You need to write some code yourself that does that. How? By simply reading the document, read the posts array, do the sorting in memory and then write the document containing the sorted array back to Firestore.

    If you find yourself in a position where you need to update an object within an array of objects, then I recommend you check the following article:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search