You can use the sample function from the Underscore library in TypeScript to randomly select one or multiple elements from an array.
Here's an example:
index.ts304 chars12 lines
In this example, we import the Underscore library using import * as _ from 'underscore';. We then declare an array myArray with some sample data.
To select one random element from the array, we simply call _.sample(myArray);. To select multiple random elements, we pass in an additional parameter indicating how many elements we want to select, like so: _.sample(myArray, 2);.
The sample method supports arrays and objects. If you pass an object to the sample method, you will get an array of random values from the object.
gistlibby LogSnag