Search code examples
javascriptrandom

Selected a random number from a set


I want to select a random number out of a set. For example from the set {8, 6, 1, 7}.


Solution

  • You can use following function to get a random number out of a set:

    function getRndmFromSet(set)
    {
        var rndm = Math.floor(Math.random() * set.length);
        return set[rndm];
    }
    

    in your case the call would be getRndmFromSet([8,6,1,7])

    Try the jsFiddle

    Note: if your "set" is actually a Set object and not an array, you'd use .size instead of .length.