javascriptselectrandom

How to choose a weighted random array element in Javascript?


For example: There are four items in an array. I want to get one randomly, like this:

array items = [
    "bike"    //40% chance to select
    "car"     //30% chance to select
    "boat"    //15% chance to select
    "train"   //10% chance to select
    "plane"   //5%  chance to select
]

Solution

  • Sure you can. Here's a simple code to do it:

        // Object or Array. Which every you prefer.
    var item = {
        bike:40, // Weighted Probability
        care:30, // Weighted Probability
        boat:15, // Weighted Probability
        train:10, // Weighted Probability
        plane:5 // Weighted Probability
        // The number is not really percentage. You could put whatever number you want.
        // Any number less than 1 will never occur
    };
    
    function get(input) {
        var array = []; // Just Checking...
        for(var item in input) {
            if ( input.hasOwnProperty(item) ) { // Safety
                for( var i=0; i<input[item]; i++ ) {
                    array.push(item);
                }
            }
        }
        // Probability Fun
        return array[Math.floor(Math.random() * array.length)];
    }
    
    console.log(get(item)); // See Console.