Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to choose a weighted random array element in javascript

function weighted_random(options) {
    var i;

    var weights = [];

    for (i = 0; i < options.length; i++)
        weights[i] = options[i].weight + (weights[i - 1] || 0);
    
    var random = Math.random() * weights[weights.length - 1];
    
    for (i = 0; i < weights.length; i++)
        if (weights[i] > random)
            break;
    
    return options[i].item;
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: Using the forEach function In JavaScript 
Javascript :: javascript show alert if browser is not google chrome 
Javascript :: how to run javascript in terminal 
Javascript :: Slice and Splice -Javascript 2 
Javascript :: split array by character javascript 
Javascript :: js convert string to number 
Javascript :: TypeError: expressValidator is not a function 
Javascript :: js promise example 
Javascript :: select and select based on value in jquery 
Javascript :: are you sure alert js 
Javascript :: how to assign an rest operator in javascript 
Javascript :: what is local storage and session storage in javascript 
Javascript :: regular function javascript 
Javascript :: anti aliasing 
Javascript :: check if string contains url 
Javascript :: react native 
Javascript :: javascript document get by attribute 
Javascript :: react native push notifications npm 
Javascript :: nodejs debug 
Javascript :: how to check empty string array in javascript 
Javascript :: javascrip functions parameters 
Javascript :: moment isbetween 
Javascript :: object properties 
Javascript :: how to build a string javascript es6 
Javascript :: double click react 
Javascript :: set className with ref react 
Javascript :: how to name a file path in document.geteleementbyid 
Javascript :: javascript dom methods list 
Javascript :: uppercase each word javascript 
Javascript :: convert json to arraylist java 
ADD CONTENT
Topic
Content
Source link
Name
5+8 =