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

7
  • Randomly sort (shuffle) the array and take the first x objects. Simple and avoids duplicates. Commented Nov 16, 2022 at 8:08
  • Can you post what you've tried already and we can have a look. Commented Nov 16, 2022 at 8:08
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… where min is 0 and max is length of array minus 1 Commented Nov 16, 2022 at 8:08
  • 2
    What have you tried so far? Please add some code, see stackoverflow.com/help/how-to-ask Commented Nov 16, 2022 at 8:09
  • Provide sample array data, btw you are probably asking for shuffling an array Commented Nov 16, 2022 at 8:10

1 Answer 1

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)
}

Sign up to request clarification or add additional context in comments.

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.