Monday, June 15, 2026
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
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS