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

484
Visualizações
Sort the state (array of objects) by date in React

Let's say you are given an array of objects in your React state, like this:

[
    {
      "id": "…",
      "title": "Brief history of Space Shuttle program",
      "date": "2016-10-29 19:00:00+01:00",
      "venue": "NASA History Museum"
    },
    {
      "id": "…",
      "title": "Why did the Challenger explode?",
      "date": "2016-11-31 18:30:00+01:00",
      "venue": "Albert II Library Building"
    }
  ]

Now you want to sort this by date, let's say you have a forum or something similar, where the first post should be the newest according to date.

How would you sort it? This was my attempt:

function sortExample (dataToSort) {
        let test = [...dataToSort];
        test.sort((a,b) => new Date(a.date) - new Date(b.date)
    }

Unfortunately, that didn't work out quite well. And most importantly, where would you place this function? I put it in my useEffect, that didn't seem to work for me either.

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

0

You have two options:

  1. Sort it before you setState, this is recommended if you only need the data in this order everywhere.
  2. Sort it where you use the data but keep the original data as is in the state.

Say we have:

const [dataInState, setDataInState] = useState([]);

First one:

useEffect(() => {
  fetch("/data")
    .then(res => res.json())
    .then(json => setDataInState(json.sort(myCompareFunc))
}, [])

Second one:

Set state as usual, then in component body, before return:

const sortedData = [...dataInState].sort(myCompareFunc)

Now you can use sortedData in JSX or elsewhere.

I recommend the first one due to performance reasons.

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