skip to Main Content

i am creating a quiz app which has an array that includes five questions but i want the five questions to display randomly but all the 5 questions at the same time

const randomQuestion = (array) => {
    let random = array[Math.floor(Math.random() * array.length)]
    return random
}
const [current, setCurrent] = useState(() => randomQuestion(questions));

3

Answers


  1. Here’s one using the array.sort method.

    array = ["Hello", "Hello2", "Hello3", "Hello4", "Hello5"];
    
    let random = array.sort(() => Math.random() - 0.5);
    
    console.log(random);
    Login or Signup to reply.
  2.     const randomQuestion = (data) => {
          return data.sort(() => (Math.random() > 0.5 ? 1 : -1));
        };
    console.log(randomQuestion([2, 3, 4, 56, 7]));
        const [current, setCurrent] = useState(() => randomQuestion(questions))
    
    Login or Signup to reply.
  3. const randomizeArray = (array) => {
      const newArray = array.slice();
      
      for (let i = newArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
      }
      
      return newArray;
    };
    
    const questions = [
      "Question 1",
      "Question 2",
      "Question 3",
      "Question 4",
      "Question 5"
    ];
    
    const randomizedQuestions = randomizeArray(questions);
    console.log(randomizedQuestions);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search