0

I have an array with 10 elements, and I want to draw 5 different elements from the array without repeating.

I tried with this code, but this solution can repeat the drawn values:

var myArray = ['1', '2' ....];

for (var i=1; i <= 5; i++)
{
var randomItem = myArray[Math.floor(Math.random()*myArray.length)];
console.log(randomItem );
}
Nope
  • 22,147
  • 7
  • 47
  • 72
Pat
  • 117
  • 1
  • 9
  • It would be fairly easy to put the drawn values into another array and check if the element has already been drawn before. Or you could remove the values from the original array so they are not available anymore. – Taplar May 21 '18 at 14:39
  • 1
    Randomize the array, pick the top 5. [**https://stackoverflow.com/a/12646864/448144**](https://stackoverflow.com/a/12646864/448144) – Nope May 21 '18 at 14:42
  • Using the shuffle answer linked above, something similar to this gets you an array of 5 random elements from your source array you then can iterate over: `var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; shuffleArray(arr); var top5 = arr.slice(0, 5);` – Nope May 21 '18 at 14:56

0 Answers0