This question already has an answer here:
- Getting random value from an array 6 answers
var items = Array(523,3452,334,31,...5346);
How do I get random item from items
?
I am using jQuery, so answers involving jQuery are welcome.
This question already has an answer here:
How do I get random item from I am using jQuery, so answers involving jQuery are welcome. |
|||||||||||||||||||||
marked as duplicate by royhowie, Denys Séguret May 22 at 8:42This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question. |
|||||||||||||||||||||
|
|
|||||||||||||||||
|
If you really must use jQuery to solve this problem:
This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value! For extra fun, the array return is generated by calling the function recursively based on the array's length :) Working demo at http://jsfiddle.net/2eyQX/ |
|||||||||||||||||||||
|
Use underscore (or loDash :)):
Or to shuffle an entire array:
|
|||||||||||||||||||||
|
|
|||
|
|
|||
|
jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,
|
||||
|
credit:
|
|||||
|
Here's yet another way:
|
|||||||||
|
Shorter:
|
|||||||||||||
|
1. solution: define Array prototype
that will work on inline arrays
and of course predefined arrays
2. solution: define custom function that accepts list and returns element
|
|||
|
If you are using node.js, you can use unique-random-array. It simply picks something random from an array. |
|||
|
An alternate way would be to add a method to the Array prototype:
|
|||||||||||||||||
|
|
||||
|