Cédric Hadjian
Cédric Hadjian

Reputation: 47

Generating a UNIQUE random number to execute random images in express EJS (node)

  <body>
<div><% for(var i=0;i<pictures.length;i++){ %>
    <img src="images\<%= Math.floor((Math.random() * pictures.length) + 1) %>.jpg">
<%}%>
</div>

Here, Math.random is executing 3 random images but NOT unique. How can I generate unique numbers so that the images execute uniquely ?

Upvotes: 0

Views: 1984

Answers (1)

Dennington-bear
Dennington-bear

Reputation: 1782

So this isn't possible without an array to store your random numbers(If i haven't misunderstood the question). So essentially what you are doing is creating an array and storing the generated random numbers. Then if the numbers are 'unique' add them to the array. Then loop through the array construct a source string for the image tag and then just call the image tag with the constructed source.

    <% var arr = [] %>
    //<!-- Make the while loop the size you eg. how many images you want shown.
    // Here it is the length of the amount of pictures change it to suit your needs -->
        <% while(arr.length < pictures.length ){
            //<!-- Create your random number -->
            var randomNum = Math.floor((Math.random() * pictures.length) + 1);
            //<!-- If the random number is not in the array -->
            if(arr.indexOf(randomNum) == -1){
                // Add the random number to the array
                arr.push(randomNum);
            }
        } %>
        <!-- Loop through the array -->
        <%arr.forEach(function(number){ %>
            <!-- Construct image source -->
            <% var source = "images/"+number+".jpg"; %>
            <!-- Create the image using the constructed source -->
            <img src=<%=source%>>
        <%});%>

Upvotes: 1

Related Questions