Load random images from folder but without repeat using javascript math.floor( math.random) function

Viewed 79

I'm new to javascript and webdev in general. Im also new here on stackoverflow. Its great!

I have found a snippet of javascript code that is working well for what I'm trying to achieve. The script shows random images from a folder but i need it to not repeat the images.

This is the script.

var random_images_array = ["smile.gif", "frown.gif", "grim.gif", "bomb.gif"];

function getRandomImage(imgAr, path) {
    path = path || "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();
}

I just can't figure out how to make it not repeat the images. I have read some solutions online but i guess im not there yet to fully grasp and recreate a working solution.

2 Answers

Remove the image from the array once you picked it

var random_images_array = ["smile.gif", "frown.gif", "grim.gif", "bomb.gif"];

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

    /* remove  1 item from index <num> */
    random_images_array.splice(num, 1);

    document.body.innerHTML += imgStr;
    
}

or shuffle the array and every time you call the function you only retrieve an element using pop() until the array is not empty.

Try this: Everytime you output image it gets added to a usedImages array, and then before new image outputed - check if already been used by comparing with the new array (usedImages)

var random_images_array = [
    "smile.gif",
    "frown.gif",
    "grim.gif",
    "bomb.gif",
  ];
  let usedImages = [];
  function getRandomImage(imgAr, path) {
    path = path || "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);
    if (usedImages.includes(imgStr)) {
      console.log("in there");
    } else {
      usedImages.push(imgStr);
      console.log(`Used Images: ${usedImages}`);
    }
    document.close();
  }
Related