VOOZH about

URL: https://www.geeksforgeeks.org/javascript/lodash-_-samplesize-method/

⇱ Lodash _.sampleSize() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lodash _.sampleSize() Method

Last Updated : 3 Sep, 2024

Lodash's _.sampleSize() method returns an array of a specified number (n) of random, unique elements from a collection (array, object, or string). It ensures no duplicates and handles empty collections by returning an empty array.

Syntax:

_.sampleSize(array, n);

Parameters:

  • 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: In this example, we are printing the random elements of the given array in the console by the use of the lodash _.sampleSize() method.

Output:

[10, 13]

Example 2: In this example, we are printing the random elements of the given array in the console by the use of the lodash _.sampleSize() method.

Output:

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

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

Comment