How to get a number of random elements from an array?
Try this non-destructive (and fast) function:
function getRandom(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len)
throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
return result;
}
Get a random item from a JavaScript array
var item = items[Math.floor(Math.random()*items.length)];
How to get random elements from an array
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.
Getting a random value from a JavaScript array
It's a simple one-liner:
const randomElement = array[Math.floor(Math.random() * array.length)];
For example:
const months = ["January", "February", "March", "April", "May", "June", "July"];
const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);
Get random elements from array in Swift
Xcode 11 • Swift 5.1
extension Collection {
func choose(_ n: Int) -> ArraySlice<Element> { shuffled().prefix(n) }
}
Playground testing
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
let shuffledAlphabet = alphabet.shuffled() // "O", "X", "L", "D", "N", "K", "R", "E", "S", "Z", "I", "T", "H", "C", "U", "B", "W", "M", "Q", "Y", "V", "A", "G", "P", "F", "J"]
let letter = alphabet.randomElement() // "D"
var numbers = Array(0...9)
let shuffledNumbers = numbers.shuffled()
shuffledNumbers // [8, 9, 3, 6, 0, 1, 4, 2, 5, 7]
numbers // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers.shuffle() // mutate it [6, 0, 2, 3, 9, 1, 5, 7, 4, 8]
numbers // [6, 0, 2, 3, 9, 1, 5, 7, 4, 8]
let pick3numbers = numbers.choose(3) // [8, 9, 2]
extension RangeReplaceableCollection {
/// Returns a new Collection shuffled
var shuffled: Self { .init(shuffled()) }
/// Shuffles this Collection in place
@discardableResult
mutating func shuffledInPlace() -> Self {
self = shuffled
return self
}
func choose(_ n: Int) -> SubSequence { shuffled.prefix(n) }
}
var alphabetString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let shuffledAlphabetString = alphabetString.shuffled // "DRGXNSJLFQHPUZTBKVMYAWEICO"
let character = alphabetString.randomElement() // "K"
alphabetString.shuffledInPlace() // mutate it "WYQVBLGZKPFUJTHOXERADMCINS"
alphabetString // "WYQVBLGZKPFUJTHOXERADMCINS"
let pick3Characters = alphabetString.choose(3) // "VYA"
Picking 2 random elements from array
do NOT use loops and comparisons. Instead
- shuffle the array
- take first two elements
pick a random item from a javascript array
Use Math.random * the length of the array, rounded down, as an index into the array.
Like this:
var answers = [ "Hey", "Howdy", "Hello There", "Wotcha", "Alright gov'nor"]
var randomAnswer = answers[Math.floor(Math.random() * answers.length)];
console.log(randomAnswer);
Related Topics
Encryption in JavaScript and Decryption With PHP
How to Make JavaScript Execute After Page Load
How to Change the Href Attribute For a Hyperlink Using Jquery
How to Stop Event Propagation With Inline Onclick Attribute
Displaying Pdf from Arraybuffer
Why Isn't My JavaScript Working in Jsfiddle
How to Add Onload Event to a Div Element
How to Change the Text of a Span Element Using JavaScript
How to Load an HTML Page in a Div Using JavaScript
Jquery Disable/Enable Submit Button
Why Is the Value of My Input Always Empty If I Store It in a Variable
How to Get a Number of Random Elements from an Array
Refresh/Reload the Content in Div Using Jquery/Ajax
Good Tutorial For Using Html5 History API (Pushstate)
Remember and Repopulate File Input