Consider:
var myArray = ['January', 'February', 'March'];
How can I select a random value from this array using JavaScript?
Consider:
var myArray = ['January', 'February', 'March'];
How can I select a random value from this array using JavaScript?
Recursive, standalone function which can return any number of items (identical to lodash.sampleSize):
Prototype Method
If you plan on getting a random value a lot, you might want to define a function for it.
First, put this in your code somewhere:
Now:
Code released into the public domain under the terms of the CC0 1.0 license.
Editing Array prototype can be harmful. Here it is a simple function to do the job.
Usage:
Here is an example of how to do it:
If you've already got underscore or lodash included in your project you can use
_.sample
.If you need to get more than one item randomly, you can pass that as a second argument in underscore:
or use the
_.sampleSize
method in lodash:Say you want to choose a random item that is different from the last time (not really random, but still a common requirement)...
Building upon the answer by @Markus, we can add another prototype function:
And implement like so: