0

I am making a quiz app in react native, it has this array of objects in which each object contains a question statement,choices and the correct choice. There will be total 15 objects in this, but i require a new array that contains only 5 of the objects of this array. They should be selected at random everytime i start the quiz. How to get that array, help

const questions = [
    new quizQuestions(
        'What is capital of Pakistan?',
        ['Karachi', 'Islamabad', 'Lahore', 'Peshawar'],
        'Islamabad',
    ),
    new quizQuestions(
        'What is capital of India?',
        ['delhi', 'Islamabad', 'zcjzj', 'Peshawar'],
        'delhi',
    ),
    new quizQuestions(
        'What is capital of Pakistan?',
        ['Karachi', 'Islamabad', 'Lahore', 'Peshawar'],
        'Islamabad',
    ),
]

4 Answers 4

2

use JS random method to generate random numbers from 0 to 15

//your whole set of questions array
    const questions = [
        new quizQuestions(
            'What is capital of Pakistan?',
            ['Karachi', 'Islamabad', 'Lahore', 'Peshawar'],
            'Islamabad',
        ),
        new quizQuestions(
            'What is capital of India?',
            ['delhi', 'Islamabad', 'zcjzj', 'Peshawar'],
            'delhi',
        ),
        new quizQuestions(
            'What is capital of Pakistan?',
            ['Karachi', 'Islamabad', 'Lahore', 'Peshawar'],
            'Islamabad',
        ),
    ];

//random 5 question array

const selectedQuestionArr = [];
let addedIndex = [];
for (var i = 0; i < 5; i++) {
  let randomIdx;
  do {

    randomIdx = Math.floor(Math.random() * 15);
  }
  while(addedIndex.indexOf(randomIdx) > -1);

  //record added index to not include it in the next cycle
  addedIndex.push(randomIdx);

  //push the randomly selected question
  selectedQuestionArr.push(questions[randomIdx]);
}

console.log(selectedQuestionArr);
Sign up to request clarification or add additional context in comments.

5 Comments

this might repeat some question if Math.random returns old index value. Wont it?
@MoeezAtlas I modified the answer
yeah i think this works. i changed randomIdx.push(randomIdx) to addedindex.push(randomIdx) as previously got error
@MoeezAtlas isn't this solution helped you?
no way to accept 2 answers, you should decide which answer would give you the best and reliable solution for your current problem
1

Very much random what you need.

Using generator function:

const questions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
function* randomise(arr, numOfElem) {
  // Create a copy of question so that wont effect actual array
  let copyArray = [...arr];

  // Use copyArray to generate random as closure, so that it never go out of index
  const getRandom = () => Math.floor(Math.random() * copyArray.length);
  // This is generator function run always
  while (true) {
    // If numOfElem is greater, then clone again

    // suppose you have 15 question but you take 6. SO after 2 iteration, copyArray will have only 3 element so clone again
    if (numOfElem > copyArray.length) {
      // Clone again
      copyArray = [...arr];
    }
    // pick 5 random data.
    let result = [];
    for (let i = 0; i < numOfElem; i++) {
      result.push(copyArray.splice(getRandom(), 1)[0]);
    }
    yield result;
  }
}

const questionGenerator = randomise(questions, 5);
console.log(questionGenerator.next().value); // random [ 11, 3, 7, 2, 8 ]

console.log(questionGenerator.next().value); // random [ 12, 13, 14, 9, 5 ]

console.log(questionGenerator.next().value); // random [ 6, 1, 4, 15, 10 ]

console.log(questionGenerator.next().value); // random [ 14, 12, 8, 2, 13 ]

console.log(questionGenerator.next().value); // random [ 9, 3, 10, 6, 11 ]

Same but without generator function.

const questions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const randomise = (arr, numOfElem) => {
  let copyArray = [...arr];
  const getRandom = () => Math.floor(Math.random() * copyArray.length);
  return () => {
    // If numOfElem is greater, then clone again

    // suppose you have 15 question but you take 6. SO after 2 iteration, copyArray will have only 3 element so clone again
    if (numOfElem > copyArray.length) {
      // Clone again
      copyArray = [...arr];
    }
    // pick 5 random data.
    let result = [];
    for (let i = 0; i < numOfElem; i++) {
      result.push(copyArray.splice(getRandom(), 1)[0]);
    }
    return result;
  };
};
const questionGenerator = randomise(questions, 5);
console.log(questionGenerator()); // random [ 11, 3, 7, 2, 8 ]

console.log(questionGenerator()); // random [ 12, 13, 14, 9, 5 ]

console.log(questionGenerator()); // random [ 6, 1, 4, 15, 10 ]

console.log(questionGenerator()); // random [ 14, 12, 8, 2, 13 ]

console.log(questionGenerator()); // random [ 9, 3, 10, 6, 11 ]

6 Comments

Lol! :-D let me know if you need help to understand! Please accept as answer :-) if works for you
Yeah i was just checking it inside my code it works.
i added a real generator function example. You can check that too. I add details later! as comment. You can check later.
Please check i added few comments. to help you.! cheers! keep coding!
Thanks bro comments help a lot :)
|
1

For your particular case, i couldn't find any lodash function for this i have implemented my own javascript logic for this you can have a look.

https://codesandbox.io/s/shuffled-array-ltzud

Comments

0

Almost a repeat of Azad's answer :D but I found our method to be very simple and straight forward. pass in selectedQuestions as an empty array

function randomizeQuestions(allQuestions,selectedQuestions,numberToSelect)
{
  selectedIndex = [];
  var randIndex;
  for(var i = 0; i < numberToSelect; i++)
  {
  
	  do{
	     randIndex = Math.floor(Math.random() * allQuestions.length);
	  }while(selectedIndex.includes(randIndex));

	  selectedIndex.push(randIndex);
	  selectedQuestions.push(allQuestions[randIndex]); 
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.