0
        var name = ['C1', 'C2', 'C3'][Math.floor(Math.random() * 3)]
        var bgimg = ['C1bg.jpeg', 'C2bg.jpeg', 'C3bg.jpeg'][Math.floor(Math.random() * 3)]
        var profile_image_url = ['C1logo.png', 'C2logo.png', 'C3logo.png'][Math.floor(Math.random() * 3)]
        var description = ['C1 desc', 'C2 desc', 'C3 desc'][Math.floor(Math.random() * 3)]

Please mind the bad example. How would you make the variables be random with their other respective variables, so a C1 name would be with a C1 logo & desc rather than every part to be random?

Found How to get n no elements randomly from an array and Getting a random value from a JavaScript array, but couldn't find how to do so as a set of variables?

Levi Josman
  • 85
  • 1
  • 9
  • 4
    Can't you do: `var random = Math.floor(Math.random() * 3)` and then use that variable to access the index? I'd also suggest using the length instead of a hardcoded 3 – Axnyff Mar 01 '18 at 17:06
  • `var random = Math.floor(Math.random() * 3);` and then `var name = ['C1,'C2','C3''][random], etc...`? Or exactly what @Axnff just said. – somethinghere Mar 01 '18 at 17:06
  • 1
    Axnyfff - should make your comment into an answer. @Levi accept his, he got there before me! – Toby Mar 01 '18 at 17:13

4 Answers4

1
var bgimgs = ['C1bg.jpeg', 'C2bg.jpeg', 'C3bg.jpeg'];
var names =  ['C1', 'C2', 'C3'];
var profile_image_urls = ['C1logo.png', 'C2logo.png', 'C3logo.png'];
var descriptions = ['C1 desc', 'C2 desc', 'C3 desc'];
var rand = Math.floor(Math.random()*bgimg.length);
var bgimg = bgimgs[random];
var name = bgimgs[random];
var profile_image_url = profile_image_urls[random];
var description = descriptions[random];
Toby
  • 1,537
  • 10
  • 19
0

Try This -

var arrIndex = Math.floor(Math.random() * 3)

Then Access the Set of Variable with this random index like -

name[arrIndex],bgimg[arrIndex],profile_img_url[arrIndex],description[arrIndex]
vishugosain
  • 180
  • 1
  • 9
0

Here you go.

Function that takes as many arrays as you want and returns new array as as set of random array items from provided arrays.

const name = ['C1', 'C2', 'C3'];
const bgimg = ['C1bg.jpeg', 'C2bg.jpeg', 'C3bg.jpeg'];
const profile_image_url = ['C1logo.png', 'C2logo.png', 'C3logo.png'];
const description = ['C1 desc', 'C2 desc', 'C3 desc'];


const getRandomSet = (...set) => {
  let randomSet = [];
  [...set].forEach( set => {
    const randomIndex = Math.floor(Math.random() * set.length);
    randomSet.push(set[randomIndex]);
  });
  
  return randomSet;
}

const radnomSetFromArray = getRandomSet(name, bgimg, profile_image_url, description); 

console.log(radnomSetFromArray);
Nikola Mitic
  • 1,298
  • 3
  • 11
  • 23
0

Better way is work with array of Objects?

var objs = [
    {name: 'Obj 1', img: 'Obj image 1'},
    {name: 'Obj 2', img: 'Obj image 2'},
    {name: 'Obj 3', img: 'Obj image 3'}
];

var sortObj = objs[Math.floor(Math.random()*objs.length)];
cau
  • 572
  • 3
  • 9