Lodash | _.sampleSize() Method
Lodash _.sampleSize() method is used to give an array of n random elements from the given array.
Syntax:
_.sampleSize(array, n);
Parameters:
- array: This parameter holds the sample collection.
- n: This parameter holds the number of elements to sample.
Return Value:
This method returns an array of n random elements.
Example 1: In this example, we are printing the random elements of the given array in the console by the use of the lodash _.sampleSize() method.
javascript
const _ = require( 'lodash' ); let x = [1, 2, 7, 10, 13, 15]; let result = _.sampleSize(x, 2); console.log(result); |
Output:
[10, 13]
Example 2: In this example, we are printing the random elements of the given array in the console by the use of the lodash _.sampleSize() method.
javascript
const _ = require( 'lodash' ); let x = [ 'mango' , 'apple' , 'banana' , 'orange' , 'grapes' ]; let result = _.sampleSize(x, 3); console.log(result); |
Output:
[ 'grapes', 'orange', 'banana' ]
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Reference: https://lodash.com/docs/4.17.15#sampleSize