0

I need it to make a quiz project.. I want random selection of questions from like 30 blocks of objects in an array....

Tried a lot but couldnt find a way to randomly select it... I tried many ways yt tutorials... But there are none meeting my requirements

  • Randomly sort ([shuffle](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array)) the array and take the first x objects. Simple and avoids duplicates. – Robby Cornelissen Nov 16 '22 at 08:08
  • Can you post what you've tried already and we can have a look. – Adam Nov 16 '22 at 08:08
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_number_between_two_values where min is 0 and max is length of array minus 1 – Natrium Nov 16 '22 at 08:08
  • 2
    What have you tried so far? Please add some code, see https://stackoverflow.com/help/how-to-ask – Ingo Steinke Nov 16 '22 at 08:09
  • Provide sample array data, btw you are probably asking for shuffling an array – Harendra Chauhan Nov 16 '22 at 08:10
  • Perhaps have a look at this? https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – Adam Nov 16 '22 at 08:11
  • Does this answer your question? [Get a random item from a JavaScript array](https://stackoverflow.com/questions/5915096/get-a-random-item-from-a-javascript-array) – Usitha Indeewara Nov 16 '22 at 12:44

1 Answers1

1

You can get a random index using

let i = Math.floor(Math.random() * array.length),

then you should remove the elment from the array maybe using arr.splice(i ,1).

This could be a sample:

let arr = [1,2,3,4,5];


for(let n in arr)
  removeRandom(arr);


function removeRandom(arr){

  let i = Math.floor(Math.random() * arr.length);

  let str= "pre "

  for(let n in arr)
   str += arr[n] ;
  
  console.log("str "+str)
  console.log("arr[i] " + arr[i]);

  arr.splice(i ,1);
 
  str= "post "

  for(let n in arr)
   str += arr[n] ;
  
  console.log("str "+str)
}
Matt
  • 95
  • 10