Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
Arrange Chat Messages By Date

I am working with Vue, but this is a general javascript question. I make a call to an api to get cat messages for a chat UI. The initial call returns an array of objects where each object is a chat message object as below.

data: [
  0: {id: 1, created_at: "2022-05-20T15:12:40.000000Z", updated_at: "2022-05-20T17:18:03.000000Z",…}
  1: {id: 2, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…}
  2: {id: 3, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…}
  3: {id: 4, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…}
]

I initial wanted to format the message so they can be grouped by their dates in the chat window. This is the code I used to group them

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 will first take the each chat object an convert their updated_at and created_at to a date string and then group the array using the updated_at. The result was as follows:

formattedChats = {
  Fri Jun 24 2022: [
    {...}, {...
  ]
  Fri May 20 2022:[
    {...}, {...
  ]
  Mon Jun 27 2022:Array[
    {...}, {...
  ]
  Sat May 21 2022:Array[
    {...}, {...
  ]
  Tue Jun 28 2022:Array[
    {...}, {...
  ]
}

If you notice, the problem I am facing is that the dates are not arranged in any order. it doesnt make sense to render it to the UI like this because the resulting chats with not be arranged by date. This is how the UI should lookchat window sample

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to use arrays (or a map) to keep the order sorted. I would use an array of arrays. First you need to sort the data on date (I used updated_at, which I made of type Date in the data array). Then iterate over the sorted array. See snippet below.

const data = [{
    id: 1,
    updated_at: new Date("2022-05-21T15:12:40.000000Z"),
    created_at: "2022-05-20T17:18:03.000000Z"
  },
  {
    id: 2,
    updated_at: new Date("2022-05-20T15:12:41.000000Z"),
    created_at: "2022-05-20T17:18:04.000000Z"
  },
  {
    id: 3,
    updated_at: new Date("2022-05-23T15:12:41.000000Z"),
    created_at: "2022-05-20T17:18:04.000000Z"
  },
  {
    id: 4,
    updated_at: new Date("2022-05-21T15:12:41.000000Z"),
    created_at: "2022-05-20T17:18:04.000000Z"
  },
]

const sortedData = data.sort(
  (a, b) => Number(a.updated_at) - Number(b.updated_at),
);


let currentDay = sortedData[0].updated_at;

const stillCurrentDay = (dayOfMessage) => {
  return dayOfMessage.getFullYear() === currentDay.getFullYear() &&
    dayOfMessage.getMonth() === currentDay.getMonth() &&
    dayOfMessage.getDate() === currentDay.getDate()
}

let dayMessageArray = [];
const fullMessageArray = [];

const createMessagesArray = (messages) => {
  const newDay = {};
  newDay[currentDay.toISOString().split('T')[0]] = messages;
  fullMessageArray.push(newDay);
}

sortedData.forEach(message => {
  if (!stillCurrentDay(message.updated_at)) {
    createMessagesArray(dayMessageArray);
    currentDay = message.updated_at;
    dayMessageArray = [];
  }

  dayMessageArray.push(message);
});

createMessagesArray(dayMessageArray);

console.log(fullMessageArray);

Hope this helps. Perhaps there are easier ways, please let me know.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda