Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
react trivia question options mappink splice issues

I am trying to randomize questions option but ı cant actually also app rendering themself 4 times. how to solve? This is my first question on stackowerflow.

const [startPage,setStartPage]=React.useState(false)
const [questionsData,setQueationsData]=React.useState([])
  
React.useEffect(()=>{
  fetch("https://opentdb.com/api.php?amount=1&type=multiple")
  .then(res => res.json())
  .then(data => (setQueationsData(data.results[0])))
},[1])
  
console.log(questionsData)
  
  
function question(){
  //! I am trying top arrange randomly answer but not easy 
    
  const incorrect_answers=questionsData.incorrect_answers
  console.log(incorrect_answers) 
  
  const correct_answer=questionsData.correct_answer
  console.log(correct_answer) 
  const answer = incorrect_answers;
  answer.splice(Math.floor(Math.random() * (incorrect_answers.length + 1)), 0,correct_answer);
  console.log(answer) 


  return (<h3>{questionsData.question}</h3>)

  return (answer.map(answer=>{ return ( <h2>{answer}</h2>)}))
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

What you can do is to have a separate function e.g. getAnswers() which will provide an array with shuffled values of all possible answers. In this functions you could have something like:

const getAnswers = () => {
    let incorrectAnswers = questionsData.incorrect_answers
    let correctAnswer = questionsData.correct_answer
    let answers = [];
    return answers = shuffle(incorrectAnswers.concat(correctAnswer)
  }

Here you have a function which collects all possible answers in one array, pass this array into a shuffle() functions and then returns the answers in random order.

A possible shuffle() functions could be:

shuffle(array){
  var currentIndex = array.length, temporaryValue, randomIndex;

  while (0 !== currentIndex) {

    // Pick a random available number
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!