HomeLanguagesJavascriptLodash _.sample() Method

Lodash _.sample() Method

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.

RELATED ARTICLES

Most Popular

Dominic
32725 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7103 POSTS0 COMMENTS
Nicole Veronica
12241 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12326 POSTS0 COMMENTS
Shaida Kate Naidoo
7216 POSTS0 COMMENTS
Ted Musemwa
7476 POSTS0 COMMENTS
Thapelo Manthata
7200 POSTS0 COMMENTS
Umr Jansen
7176 POSTS0 COMMENTS