Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get random elements from an array [duplicate]

Tags:

javascript

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.

like image 781
geef Avatar asked Aug 23 '11 09:08

geef


People also ask

Can we access elements randomly in an array?

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.

How do you select a random value from an array in Python?

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.


1 Answers

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.

like image 141
JJJ Avatar answered Oct 06 '22 15:10

JJJ