Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.
The _.sample() method will provide a random element from collection.
Syntax:
_.sample(collection)
Parameters: This method accepts single parameter as mentioned above and described below:
- collection: This parameter holds the collection to sample.
Return Value: This method is used to return the random element.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
// Requiring the lodash library const _ = require( "lodash" ); // Original array var array1 = ([ 3, 6, 9, 12 ]); // Use of _.sample() method let gfg = _.sample(array1); // Printing original Array console.log( "original array1: " , array1) // Printing the output console.log(gfg); |
Output:
original array1: [ 3, 6, 9, 12 ] 12
Example 2:
javascript
// Requiring the lodash library const _ = require( "lodash" ); // Original array var array1 = ([ 'mon' , 'tue' , 'wed' , 'thu' , 'fri' , 'sat' , 'sun' ]); // Use of _.sample() method let gfg = _.sample(array1); // Printing original Array console.log( "original array1: " , array1) // Printing the output console.log(gfg); |
Output:
original array1: [ 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] mon
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.