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

183
Visualizações
How to shuffle nested array with useState

I'm making a Quiz app in react native and I want to shuffle the order of questions each time someone picks the quiz. I was thinking about using shuffle from lodash but I'm not totally sure how to do for nested array.

const getTest = async () => {

     try {
        const response = await fetch('https://tgryl.pl/quiz/test/'.concat(route.params.testId));
        const json = await response.json();
        setData(json);
     }
     catch (error) {
          console.error(error);
     } 
}

I was thinking about something like setData(_.shuffle(data.tasks)) ?? I have no idea

The JSON looks like this

enter image description here

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

0

Apparently the array to be shuffled is stored in the tasks property of the response object, so you should shuffle that array and assign it back to that property:

json.tasks = _.shuffle(json.tasks);
setData(json);

Even though this mutates an object and then passes it to setData (which presumably calls setState/useState, and such mutation is usually a code smell), this is not an issue here, as this object was never used before for the state.

Unrelated, but I would not call that variable json. It is a JavaScript object. JSON is the term for the text format that the json() method retrieves from the request and converts to the object/array.

Use a name that describes the content, like quiz.

about 4 years ago · Juan Pablo Isaza Relatório

0

You don't have nested arrays, you have arrays inside of an object. That's the response data structure you're receiving.

I think this is a fun question, so here I implemented an alternative way of shuffling the questions array.

Logic

Do a loop through all the questions and inside of it:

  1. Generate a random index between 0 and the length of the questions array.
  2. Use pop() to remove the last element of the array and return it to the Q variable.
  3. Use splice() to add question Q to the random index generated.

const arr1 = [];
const arr2 = [
        {question: 'asd asd 1', answer: 'bla 1', duration: 10},
        {question: 'asd asd 2', answer: 'bla 2', duration: 20},
        {question: 'asd asd 3', answer: 'bla 3', duration: 15},
        {question: 'asd asd 4', answer: 'bla 4', duration: 30}
      ];
const arr3 = [];

const responseObject = {
  arr1,
  arr2,
  arr3
};
      
let questions = responseObject.arr2;

for(const question of questions){
  let randIndex = Math.round(Math.random()*(questions.length - 1));
  let Q = questions.pop(); 
  questions.splice(randIndex, 0, Q);
}

console.log(questions)

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