This question already has an answer here:
I have array
var arr = ['elem1', 'elem2', 'elem3', 'elem4', 'elem5', 'elem6', 'elem7', 'elem8'];
How could I echo 4 random elements of it using javascript?
This question already has an answer here: I have array
How could I echo 4 random elements of it using javascript? |
|||
You can use the below code to get a random element:
|
|||
|
What about this:
|
|||
|
Use inbuilt Math.Random:
|
||||
|
If you want distinct elements, you can extract them one at a time from the array
An alternative is to shuffle (sort randomly) the array then get the first 4 elements:
This answer from a question that duplicates this one is very good: http://stackoverflow.com/a/7159251/1669279 It is an improvement over the first method above:
|
||||
|
If you are trying to get 4 unique elements of that array, you should always remove the element that you randomly retrieved:
|
|||
|
You can use the below code to get a 4 random element:
|
|||
|
Array.apply( null , new Array(4) ).map( function( v ){ return arr[Math.floor( Math.random( ) * arr.length ) ];});
` – rab Nov 12 '13 at 9:24