how to use the samplesize function from the lodash library in typescript

The sampleSize function from the Lodash library in TypeScript can be used with the following steps:

  1. Install the Lodash library using npm:

    index.ts
    npm install --save lodash
    
    26 chars
    2 lines
  2. Import the sampleSize function from the Lodash library:

    index.ts
    import { sampleSize } from 'lodash';
    
    37 chars
    2 lines
  3. Use the sampleSize function on an array to return a random sample of a specified size:

    index.ts
    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const sample = sampleSize(arr, 4);
    console.log(sample); // [4, 6, 1, 9]
    
    117 chars
    4 lines

In the above example, sampleSize is used to return a random sample of size 4 from the arr array. The sample is logged to the console.

Note that the second argument passed to the sampleSize function must be a positive integer. If the value is not a positive integer, the function will return an empty array.

gistlibby LogSnag