🎲 Weighted Array
Select a random element from a weighted array.
The package is on the NPM registry as
weighted-array. Simply install it with your NPM client of choice.
First, import the module:
const weightedArray =
select() function takes an array of objects. Every object must have at least the key:
weight: number. This is a weight relative to each other object in the array.
There is also the
selectUnique*() ES6 generator which will return randomly but without sequential repeats.
Both return one object from the array, with the whole object intact.
// Import the moduleconst select =const array =weight: 1 name: 'Ben'weight: 2 name: 'Jerry'console // -> Will return Jerry twice as often as Ben