skip to Main Content

I’m trying to map my array of messages so that the newest message comes first.
I’ve tried a few ways but nothing seams to change, any ideas what I’m doing wrong?

const feedSort = [...feed].sort((a, b) => a.createdAt > b.createdAt);


{feedSort.map((data) =>
                   ......the data ......
)}

2

Answers


  1. Try this after that map loop as you write.

    const feedSort = [...feed].sort((a, b) => b.createdAt - a.createdAt);
    Login or Signup to reply.
  2. I don’t know exact behavior when you subtract Date strings in javascript, but you should subtract them as Date objects like so:

    const feedSort = [...feed].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search