Saturday, September 6, 2025
HomeLanguagesJavascriptLodash | _.sampleSize() Method

Lodash | _.sampleSize() Method

The _.sampleSize() method is used to give an array of n random elements from the given array.

Syntax:

_.sampleSize(array, n)

Parameters: This method accept two parameters as mentioned above and described below:

  • array: This parameter holds the sample collection.
  • n: This parameter holds the number of elements to sample.

Return Value: This method returns an array of n random elements.

Example 1:




const _ = require('lodash');
  
let x = [1, 2, 7, 10, 13, 15];
  
let result = _.sampleSize(x, 2);
  
console.log(result);


Here, const _ = require('lodash') is used to import the lodash library into the file.

Output:

[10, 13]

Example 2:




const _ = require('lodash');
  
let x = ['mango', 'apple', 'banana', 'orange', 'grapes'];
  
let result = _.sampleSize(x, 3);
  
console.log(result);


Output:

[ 'grapes', 'orange', 'banana' ]

Example 2:




const _ = require('lodash');
  
let x = [1, 'a', {'name': 'sampleSize'}, [1, 2, 3]];
  
let result = _.sampleSize(x, 3);
  
console.log(result);


Output:

[ { name: 'sampleSize' }, 'a', 1 ]

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.

Reference: https://lodash.com/docs/4.17.15#sampleSize

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11868 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS