Search code examples
javascriptimagefunctionshufflemethod-call

Where is my setting and calling of a shuffle array function going wrong?


I'm able to loop a function to display 5 random images. Now I want to use the same 5 images and shuffle them, where each image appears only once (giving 5! = 120 permutations).

I've found plenty of tips on how to shuffle and display random numbers (not images), but where I think my issue is is setting and then calling functions. How do I do that?

Assumptions:

  1. Between my <style> tags I need to define my shuffle function
  2. My array of images can remain as it is (since it's the same ones, clearly making sure to update any changed references form the new URL)
  3. The shuffle function gets called in the body of my page (I'm not sure about this bit)

In simple English I'm trying to achieve:

"Take the five images in the collection and put them, once only, into any order."

What happens:

Five images appear, often images are repeated.

The successful webpage has this:

    </style>
<script type="text/javascript">
// place your images in this array
var random_images_array = ['Weare.jpg', 'Always.jpg', 'There.jpg', 'For.jpg', 'You.jpg'];

function getRandomImage(imgAr, path) {
    path = path || '../Public/images/'; // default path here
    var num = Math.floor( Math.random() * imgAr.length );
    var img = imgAr[ num ];
    var imgStr = '<img src="' + path + img + '" alt = "">';
    document.write(imgStr); document.close();
}

</script>
</head>
<body>

And then this (which is, I assume the calling of the function)

<div>
    <!-- This script segment displays an image from the array -->
    <script type="text/javascript">for (i = 0; i < 5; i++) getRandomImage(random_images_array, 'images/')</script>
</div>

How can I fix this?


Solution

  • A kind commenter who deleted their answer gave me the following:

        var random_images_array = ['Weare.jpg', 'Always.jpg', 'There.jpg', 'For.jpg', 'You.jpg'];
    
    function shuffleArray(arr) {
       for (var i = arr.length - 1; i > 0; i--) {
          var j = Math.floor(Math.random() * (i + 1));
          var temp = arr[i];
          arr[i] = arr[j];
          arr[j] = temp;
       }
    }
    
    // Shuffle images here
    shuffleArray(random_images_array);
    
    function getRandomImage(imgAr, path) {
       path = path || '../Public/images/'; // default path here
       for (var i = 0; i < imgAr.length; i++) {
          var img = imgAr[i];
          var imgStr = '<img src="' + path + img + '" alt = "">';
          document.write(imgStr);
          document.close();
       }
    }
    
    getRandomImage(random_images_array, 'images/')
    

    And it worked! Thank you, mystery helper!