A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/lodash-_-samplesize-method/ below:

Lodash _.sampleSize() Method - GeeksforGeeks

Lodash _.sampleSize() Method

Last Updated : 03 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: 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.

javascript
const _ = require('lodash');

let x = [1, 2, 7, 10, 13, 15];
let result = _.sampleSize(x, 2);

console.log(result);

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.

javascript
const _ = require('lodash');

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

console.log(result);

Output:

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

Note: This 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