In Lodash, we can get a random element from an array using the following methods:
_.sample()
method_.sampleSize()
method_.sample()
method_.sample(array);
This method accepts the following parameters:
array
: This is the array from which a random element is retrieved.This method returns a random element from the array.
Let’s look at an example of getting a random element from an array using the _.sample()
method in the code snippet below.
In the HTML tab, we see the following:
lodash
script.In the JavaScript tab, we see the following:
_.sample()
method._.sampleSize()
method_.sampleSize(array, n);
This method accepts the following parameters:
array
: This is the array from which n
random elements are retrieved.n
: This is the number of random elements to be retrieved.This method returns an array containing n
random elements from the array.
Let’s look at an example of getting n
random elements from an array using the _.sampleSize()
method in the code snippet below.
In the HTML tab, we see the following:
lodash
script.In the JavaScript tab, we see the following:
n
and initialize it.n
random elements from the array using the _.sampleSize()
method.