Picking a Random Item from an Array

One way would be to shuffle the array and then remove the first three items from it: http://www.kirupa.com/html5/shuffling_array_js.htm

That would be inefficient for large sets of data, so you could just literally remove three random items using something as follows:

var myShows = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter'];

function getRandomIndex(items) {
  return Math.floor(Math.random() * items.length);
}

for (var i = 0; i < 3; i++) {
  var removedItem = myShows.splice(getRandomIndex(myShows), 1);
  document.writeln(removedItem)
}

Does this help? :smile:

Cheers,
Kirupa

1 Like