Sharon Rosario
Sharon Rosario

Reputation: 1

How to randomly select objects from an array without repeatation

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

Upvotes: 0

Views: 62

Answers (1)

Matt
Matt

Reputation: 105

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

Upvotes: 1

Related Questions