-1

So I want the elements from the students variable to be pushed into the results array in a randomised order each time the code is ran.

I'm not sure how to do this as I am pretty new to JavaScript.

Here's my code.

function getRandomElement(arr){
  return arr[Math.floor((Math.random()* arr.length))];
}

var students = ['John', 'Dan', 'Jordan', 'Matt', 'Beth'];
var results = [];

for(var ) {
results.push (getRandomElement(students)); 
}
//console.log(getRandomElement(students));

console.log(results);
Sumit Sahay
  • 504
  • 4
  • 22
illage4
  • 455
  • 5
  • 8

1 Answers1

1

Maybe this helps. It splices a random item until the original array is empty.

var students = ['John', 'Dan', 'Jordan', 'Matt', 'Beth'];
var results = [];

while (students.length) {
    results.push(students.splice(Math.floor(Math.random() * students.length), 1)[0]); 
}

document.write('<pre>' + JSON.stringify(results, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392