Sunday, November 23, 2025
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
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS