While using Vue, I encountered a general JavaScript question. I am fetching cat messages from an API for a chat interface. The initial call returns an array of objects where each object represents a chat message:
data: [
{id: 1, created_at: "2022-05-20T15:12:40.000000Z", updated_at: "2022-05-20T17:18:03.000000Z",…},
{id: 2, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…},
{id: 3, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…},
{id: 4, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…}
]
Initially, I tried to format the messages based on their dates in the chat window. Here's the code snippet I used:
This is a computed property in Vue
const formattedChats = computed(() => {
let dateFormattedMessages = messages.value.map(message => {
return {...message, updated_at: new Date(message.updated_at).toDateString(), created_at: new Date(message.created_at).toDateString()}
})
return dateFormattedMessages.reduce((total, currentValue) => {
total[currentValue.updated_at] = total[currentValue.updated_at] || [];
total[currentValue.updated_at].push(currentValue);
return total;
}, Object.create(null));
})
The above snippet first converts the updated_at
and created_at
properties of each chat object into date strings, and then groups the array by the updated_at
property.
The resulting structure looks like this:
formattedChats = {
Fri Jun 24 2022: [{...}, {...}],
Fri May 20 2022: [{...}, {...}],
Mon Jun 27 2022: [{...}, {...}],
Sat May 21 2022: [{...}, {...}],
Tue Jun 28 2022: [{...}, {...}]
}
The issue I'm facing is that the dates are not sorted in any order. This makes it difficult to render the chats in the UI as they won't be displayed chronologically. Here's how the UI should ideally appear: https://i.sstatic.net/iq0LL.png