1
var eg = "one"
var eg2 = "two"
var eg3 = "three"

function randomchoose() {
    var rand = ["eg", "eg2", "eg3"];
    var act = [eg, eg2, eg3];
    choose = rand[Math.floor(Math.random()*rand.length)]
    chosen = act[choose]
    return [chosen, choose];
}

my issue with this is that I don't know how to make "chosen" be the variable that was randomly chosen.

basically, if it rolls eg, i want chosen to be "one" and same goes for others

------EDIT------ I forgot to specify, i need it to return the variable name as "choose" and the actual value as "chosen"

Cate
  • 37
  • 6
  • 1
    What exactly do you plan to do with the returned variable name? Sounds like you should create an object instead of use multiple variables – charlietfl May 12 '18 at 12:35

4 Answers4

2

As I understood, you want to return field name and field value, which were randomly chosen. Here's a snippet:

var eg = "one"
var eg2 = "two"
var eg3 = "three"

function choseRandom() {
  var rand = ["eg", "eg2", "eg3"];
  var act = [eg, eg2, eg3];
  var chosenIndex = Math.floor(Math.random()*rand.length);
  var fieldName = rand[chosenIndex]
  var fieldValue = act[chosenIndex]
  return [fieldName, fieldValue];
}

console.log(choseRandom());
console.log(choseRandom());
console.log(choseRandom());
Krypt1
  • 1,066
  • 8
  • 14
  • What exactly doesn't work in my snippet for you? I'll update the answer if something's off, but it should work correctly. – Krypt1 May 12 '18 at 12:41
  • Ah, okay. Also I've updated the `choose` and `chosen` variables, to better reflect the purpose and made them local, instead of global ([Why are global variables considered bad practice?](https://stackoverflow.com/questions/10525582/why-are-global-variables-considered-bad-practice)). Also you might want to change the return value from array to object, but it really depends on your case I guess. – Krypt1 May 12 '18 at 12:51
  • in my case i'd need arrays, this little code is later used and requires arrays...very specific i know haha, anyway thanks a lot for the help! – Cate May 12 '18 at 12:59
1

Use an object instead of multiple variables to store the values

var data = {
  eg: "one",
  eg2: "two",
  eg3: "three"
}

function randomchoose() {
  var rand = ["eg", "eg2", "eg3"];

  choose = rand[Math.floor(Math.random() * rand.length)]
  chosen = data[choose]
  return [chosen, choose];
}

console.log(randomchoose())
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

You just need to store the random number you get and pass with the array when you need it. Here is snippet

Updated as per your question

var eg = "one"
var eg2 = "two"
var eg3 = "three"

function randomchoose() {
    var rand = ["eg", "eg2", "eg3"];
    var act = [eg, eg2, eg3];
    randomNumber = Math.floor(Math.random()*rand.length)
    chosen = act[randomNumber]
    choose = rand[randomNumber]
    return [chosen, choose];
}
console.log(randomchoose())
Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52
0

chosen = act[rand.indexOf(choose)]