Skip to content Skip to sidebar Skip to footer

How To Get A New Array Containing Some Random Elements From An Old Array In Javascript

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 objec

Solution 1:

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

//your whole set of questions arrayconst 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);

Solution 2:

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 arraylet copyArray = [...arr];

  // Use copyArray to generate random as closure, so that it never go out of indexconstgetRandom = () => Math.floor(Math.random() * copyArray.length);
  // This is generator function run alwayswhile (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 againif (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];
constrandomise = (arr, numOfElem) => {
  let copyArray = [...arr];
  constgetRandom = () => 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 againif (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 ]

Solution 3:

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

Solution 4:

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

functionrandomizeQuestions(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]); 
  }
}

Post a Comment for "How To Get A New Array Containing Some Random Elements From An Old Array In Javascript"