0

I know how to sort through an array like this

 var rand = myArray[Math.floor(Math.random() * myArray.length)];

but what I am trying to do is use this in a loop to pick values from my array that I haven't picked with this function before.

In other words, let's say my array contains apples, bananas, and oranges. i want to be able to pick all three of those out randomly, but I don't want to pick able to pick out the same one more than once.(I hope this made sense)

TandyRayes
  • 55
  • 1
  • 9

1 Answers1

1

You can remove the item from the array, so it will not be selected again

var rand = myArray.length ? myArray.splice(Math.floor(Math.random() * myArray.length), 1)[0] : undefined;

Demo: Fiddle

Note: It will modify the original array, so if you want to keep the original array as it was you need to keep a different copy

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531