Saturday, January 17, 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
32474 POSTS0 COMMENTS
Milvus
118 POSTS0 COMMENTS
Nango Kala
6846 POSTS0 COMMENTS
Nicole Veronica
11977 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12062 POSTS0 COMMENTS
Shaida Kate Naidoo
6985 POSTS0 COMMENTS
Ted Musemwa
7219 POSTS0 COMMENTS
Thapelo Manthata
6933 POSTS0 COMMENTS
Umr Jansen
6911 POSTS0 COMMENTS