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

148
Visualizações
How should I map over two arrays without ruining the order of rendered items?

I'm trying to create a chat-bot with some additional features like sending and receiving voice audio. I used two different array states for rendering the text messages and audio messages. In the render section, I map over these arrays separately.

setMessageList((prevlist) => [...prevlist, {id: uuidv4(), message: currentMessage, type: "sender",}, {id: uuidv4(), message: "response.data.data.answer", type:"reciever"}]);


     setAudioList(prevState => [
      ...prevState,
      {id: uuidv4(), audio: audioUrlQuestion, type: "sender", isLoading: isLoadedVoice} , 
      {id: uuidv4(), audio: result.data.filePath , type: "reciever", isLoading: isLoadedVoice}
    ])
 {audioList.map(item => {
            if (item.type === "sender") {
                   //render sender audio tag
            }
            if (item.type === "reciever" && isLoadedVoice === false) {
              // ...
            } else if (item.type === "reciever" && isLoadedVoice === true) {
              //
            }
          })}
          {messageList.map((item) => {
            if (item.type === "sender") {
              //show sender messages
            }
            if (item.type === "reciever" && isLoadedMessage === false) {
               // show received mesgs
            
            } else if (item.type === "reciever" && isLoadedMessage === true) {
              //
            }
          })}

However, everything works in a right order only when user just send audio/text messages without any switching. For example, if your first message is audio and the second one is text, when you want to send the third message which is an audio type again it should show the audio after the text message. But it doesn't. Instead it will appear after the first audio message(before the text one).
So, how can I render voice messages and text messages in a right order after another?

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

0

It's either sorting (constraints: ~nlogn complexity for each render, need timestamps), or putting them together into the same state array i.e.

const [allMessages, setAllMessages] = useState([]);

...

setAllMessages([...allMessages, {type: "audio", item: {id: uuidv4(), audio: audioUrlQuestion, type: "sender", isLoading: isLoadedVoice}}, {type: "audio", item: 
      {id: uuidv4(), audio: result.data.filePath , type: "reciever", isLoading: isLoadedVoice}}]);

...

setAllMessages([...allMessages, {type: "text", item: {id: uuidv4(), message: currentMessage, type: "sender",}}, {type: "text", item: {id: uuidv4(), message: "response.data.data.answer", type:"reciever"}}]);

...

 {allMessages.map(({type, item}) => {
           if (type === "audio") {
if (item.type === "sender") {
                   //render sender audio tag
            }
            if (item.type === "reciever" && isLoadedVoice === false) {
              // ...
            } else if (item.type === "reciever" && isLoadedVoice === true) {
              //
            }
           } else if (type === "text") { 
if (item.type === "sender") {
              //show sender messages
            }
            if (item.type === "reciever" && isLoadedMessage === false) {
               // show received mesgs
            
            } else if (item.type === "reciever" && isLoadedMessage === true) {
              //
            }
           }
            
          })}

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is simple Way ,

const audio = [{
    message: "Audio 1",
    time: 1
  },
  {
    message: "Audio 1",
    time: 3
  },
];
const message = [{
  mesage: "Text 1",
  time: 2
}];
[...audio,...message].sort(( a, b )=> {
  if ( a.time < b.time ){
    return -1;
  }
  if ( a.time > b.time ){
    return 1;
  }
  return 0;
}).map((item)=> console.log(item))

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