Possible Duplicate:
JavaScript: Getting random value from an array
var numbers = new Array('1','2','4','5','6','7','8','9','10');
I have a JavaScript Array and now want to randomly choose four different numbers from it and then express it on the page (through document.write
). Obviously each time the page is reloaded by the user it would show four different random numbers.
Random(direct) access implies the ability to access any entry in a array in constant time (independent of its position in the array and of array's size). And that is big advantage. It is typically contrasted to sequential access.
Use the numpy. random. choice() function to generate the random choices and samples from a NumPy multidimensional array. Using this function we can get single or multiple random numbers from the n-dimensional array with or without replacement.
You could shuffle the array and pick the first four.
numbers.sort( function() { return 0.5 - Math.random() } );
Now numbers[0]
, numbers[1]
... and so on have random and unique elements.
Note that this method may not be an optimal way to shuffle an array: see Is it correct to use JavaScript Array.sort() method for shuffling? for discussion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With