'Is there a way to find out which array the image belongs to, after loading it into an array in preload() function? - Javascript

I am trying to load multiple images from multiple folders in three different arrays like so:

function preload() 
{

for (let num=0; num<10; num++){

    array1[num] = loadImage('first/img'+ num +'.png');
  }
   
  for (let num1=0; num1<18; num1++){

    array2[num1] = loadImage('second/img'+ num1 +'.png');
  } 

  for (let num2=0; num2<25; num2++){

    array3[num2] = loadImage('third/img'+ num2 +'.png');
  }  
}

Now I want to pick a random image from a random folder. If the image belongs to array1, I want to print 'first folder'. If second, it should print 'second folder' and so on.

Is there any easier way to get this task done?



Solution 1:[1]

You can pick a random folder first, then pick a random image from it. This is the pseudo code.

const getRand = (num) => parseInt(Math.random() * num);

const folder1 = Array.from(Array(10).keys());
const folder2 = Array.from(Array(18).keys());
const folder3 = Array.from(Array(25).keys());
const allItems = [folder1, folder2, folder3];

const randInt1 = getRand(allItems.length);
const randomFolder = allItems[randInt1];
const randInt2 = getRand(randomFolder.length);
const randomImage = randomFolder[randInt2];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vicky