1

I'd like to sort these ChatListItems by the date of chat.messages.date.

{
    userChats.map(chat => (
        <ChatLink key={chat._id} to={`/chats/${chat._id}`}>
            <ChatListItem
                partnerName={pickPartnerName(
                    userName,
                    chat.userName1,
                    chat.userName2
                )}
                userImgSrc={DefaultUserAvatar}
                lastMessage={chat.messages[chat.messages.length - 1].body}
                lastMessageDate={chat.messages[
                    chat.messages.length - 1
                ].date.slice(11, 16)}
            />
        </ChatLink>
    ));
}

The db object looks like this:

const messageSchema = new mongoose.Schema({
    type: {
        type: String
    },
    body: {
        type: String
    },
    author: {
        type: String
    },
    date: {
        type: Date,
        default: Date.now
    }
});

const chatSchema = new mongoose.Schema({
    userName1: String,
    userName2: String,
    messages: [messageSchema]
});

So i would like to sort by the last date of these messages. the dates itself look like this: 2020-01-13 22:22:17.345Z

How would i accomplish this?

thanks in advance!

Sorry for my horrble question title

Here's a visual of what i'm actually trying to achieve. https://i.stack.imgur.com/zQkxl.png

  • 2
    Does this answer your question? [How to sort an array by a date property](https://stackoverflow.com/questions/10123953/how-to-sort-an-array-by-a-date-property) – Ahmet Zeybek Jan 14 '20 at 22:50
  • What have you tried already? – SOReader Jan 14 '20 at 22:54
  • thx for formating. i understand the suggested solution, but i dont understand how to implement it. As there might be two or ten or even a hundred userChats in the array. so i guess i would have to do that inside my map? – Sascha Rissling Jan 14 '20 at 22:57

1 Answers1

0

To sort your chat.messages you can process this way

chat.messages.sort((a,b)=>a.date.getTime()-b.date.getTime());

Now it is up to you to get the order you want by changing a.date.getTime()-b.date.getTime() to bdate.getTime()-a.date.getTime()

  • Hey thanks for the snippet. But i actually want to sort userChats by the date of the latest message. I've added a visual to my OP to clarify – Sascha Rissling Jan 15 '20 at 09:22