You can use the _.sample()
function in the Underscore library to randomly sample an element from a collection. Here's an example:
index.tsx313 chars12 lines
In the code above, we import the Underscore library and define a collection of numbers. We then use the _.sample()
function to sample a random element from the numbers
array, and print the sampled element to the console.
You can also use _.sample()
to sample multiple elements from a collection by specifying the number of elements to sample as the second argument:
index.tsx189 chars9 lines
In this example, we sample two random elements from the numbers
array and store them in an array called randomElements
. We then print randomElements
to the console, which will contain two randomly sampled elements from the numbers
array.
gistlibby LogSnag