0

There are 10 pictures and 10 descriptions to them. I need to randomly select a picture and description for it and render it. So, I compiled an array of objects :

 const randomPictures = [
   { 
    image: 'url1',
    description: 'description1'
   },
   {
    image: 'url2',
    description: 'description2'
   }, 
   {
    image: 'url3',
    description: 'description3'
   }
 ];

How to randomly select an object from this array and render it? Or maybe another way to get randomly picture and its description ?

SB-1994
  • 155
  • 1
  • 1
  • 6
  • Try Googling for "random element from javascript array". That will turn up things like this: https://stackoverflow.com/questions/5915096/get-random-item-from-javascript-array –  Sep 25 '17 at 20:53

2 Answers2

0

You can use math.random to generate a value between the max and min and math.floor to round to the nearest int:

Math.floor(Math.random() * (max - min) + min)
nick
  • 789
  • 1
  • 11
  • 27
0

With your given array here is an example picking a random number and getting the info of that element in the array.

const randomPictures = [
  {
    image: 'url1',
    description: 'description1'
  },
  {
    image: 'url2',
    description: 'description2'
  },
  {
    image: 'url3',
    description: 'description3'
  }
]

randNum = Math.floor(Math.random() * randomPictures.length);
console.log(randomPictures[randNum].image);
console.log(randomPictures[randNum].description);