add after ary assign assignIn assignInWith assignWith at before bind bindAll bindKey camelCase capitalize castArray ceil chain chunk clamp clone cloneDeep cloneDeepWith cloneWith compact concat conformsTo countBy create curry curryRight debounce deburr defaults defaultsDeep defer delay difference divide drop dropRight each eachRight endsWith entries entriesIn eq escape every extend extendWith fill filter find findIndex findKey findLast findLastIndex findLastKey first flatMap flatMapDeep flatMapDepth flatten flattenDeep flattenDepth flip floor forEach forEachRight forIn forInRight forOwn forOwnRight fromPairs functions functionsIn get groupBy gt gte has hasIn head inRange includes indexOf initial intersection invert invertBy invoke invokeMap isArguments isArray isArrayBuffer isArrayLike isArrayLikeObject isBoolean isBuffer isDate isElement isEmpty isEqual isEqualWith isError isFinite isFunction isInteger isLength isMap isMatch isMatchWith isNaN isNative isNil isNull isNumber isObject isObjectLike isPlainObject isRegExp isSafeInteger isSet isString isSymbol isTypedArray isUndefined isWeakMap isWeakSet join kebabCase keyBy keys keysIn last lastIndexOf lowerCase lowerFirst lt lte map mapKeys mapValues max maxBy mean meanBy memoize merge mergeWith min minBy multiply negate nth omit omitBy once orderBy overArgs pad padEnd padStart parseInt partial partialRight partition pick pickBy pull pullAll pullAllBy pullAllWith pullAt random rearg reduce reduceRight reject remove repeat replace rest result reverse round sample sampleSize set setWith shuffle size slice snakeCase some sortBy sortedIndex sortedIndexOf sortedLastIndex sortedLastIndexOf sortedUniq split spread startCase startsWith subtract sum sumBy tail take takeRight tap template throttle thru toArray toFinite toInteger toLength toLower toNumber toPairs toPairsIn toPlainObject toSafeInteger toString toUpper transform trim trimEnd trimStart truncate unary unescape union uniq uniqBy uniqWith unset unzip unzipWith update updateWith upperCase upperFirst values valuesIn without words wrap wrapperAt wrapperChain wrapperCommit wrapperFlatMap wrapperLodash wrapperNext wrapperPlant wrapperReverse wrapperToIterator wrapperValue xor zip zipObject zipObjectDeep zipWith

Lodash _.sampleSize

Overview

The lodash library provides a wide range of functions and utilities for working with arrays, objects, numbers, strings, and other data types in JavaScript. One of the functions available in the library is the _.sampleSize() method, which is designed to randomly select a specified number of values from an input collection or sequence.

The _.sampleSize() method takes two arguments: the collection or sequence to sample from, and the number of values to sample. It returns an array that contains a random selection of items from the input collection, up to the specified number.

Here is the basic syntax for using the _.sampleSize() method:

_.sampleSize(collection, [n=1])

In this syntax, collection can be an array, a string, or an object. If it is an object, only its values will be sampled. The [n=1] argument is optional and specifies the number of items to sample from the collection. If this argument is not provided, the default value of n is 1.

For example, to select two random characters from a string, you could use the following code:

const str = 'abcdefghijklmnopqrstuvwxyz';
const randomChars = _.sampleSize(str, 2);
console.log(randomChars);
// output: ["j", "f"]

In this example, the str string contains all of the lowercase letters of the alphabet. The _.sampleSize() method is used to select two random characters from this string, which are returned as an array (["j", "f"]).

Similarly, you can use the _.sampleSize() method to select a random subset of items from an array:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const randomItems = _.sampleSize(arr, 3);
console.log(randomItems);
// output: [5, 2, 8]

In this example, the arr array contains the numbers 1 through 10. The _.sampleSize() method is used to select three random numbers from this array, which are returned as an array ([5, 2, 8]).

By default, the _.sampleSize() method uses a built-in random number generator to select items from the input collection. However, you can also pass in your own custom random number generator function as a third argument to the method. This allows you to control how the selection process is performed, and can be useful if you need to create deterministic test cases or other specialized applications.

Overall, the _.sampleSize() method is a powerful and convenient way to select a random subset of values from a collection or sequence in JavaScript. It is easy to use, customizable, and provides consistent and reliable results across different platforms and environments.