Home > Software engineering >  how to make new "posts" in array as [0]?
how to make new "posts" in array as [0]?

Time:10-01

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

CodePudding user response:

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

CodePudding user response:

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:

  • Related