Open In App

Lodash _.sample() Method

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.sample() method will provide a random element from the collection.

Syntax:

_.sample(collection);

Parameters:

  • collection: This parameter holds the collection to sample.

Return Value:

This method is used to return the random element.

Example 1: In this example, we are getting a random value from an integer array by the use of the lodash _.sample() method.

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let 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: In this example, we are getting a random value from an string array by the use of the lodash _.sample() method.

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let 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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads