Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including weighted-array with all npm packages installed. Try it out:

var weightedArray = require("weighted-array")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

weighted-array v0.2.0

Select a random element from a weighted array.

🎲 Weighted Array

NPM version NPM downloads Build status Dependencies Coverage Status

Select a random element from a weighted array.

💾 Installation

The package is on the NPM registry as weighted-array. Simply install it with your NPM client of choice.

🔧 Usage

First, import the module:

const weightedArray = require('weighted-array')

The 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.

📝 Example

// Import the module
const { select } = require('weighted-array')

const array = [
  { weight: 1, name: 'Ben' },
  { weight: 2, name: 'Jerry' },

console.log(select(array)) // -> Will return Jerry twice as often as Ben

❤ Thanks

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free