Last Updated : 03 Sep, 2024
Lodash's _.sample() method randomly selects and returns a single element from a collection (array, object, or string). If the collection is empty, it returns `undefined`. It's useful for retrieving random items efficiently.
Syntax:_.sample(collection);Parameters:
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4