2

I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I accomplished

var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}

Now I want to add more options for such as books, games.. so I've created an object for it:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random. And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

Devid Farinelli
  • 7,514
  • 9
  • 42
  • 73
Timmster
  • 21
  • 1
  • 2
  • Get a random number between 0 and chooseOption.length then do chooseOption.key(random number); – LiverpoolOwen Mar 30 '17 at 10:53
  • Does this answer your question? [Pick random property from a Javascript object](https://stackoverflow.com/q/2532218/90527) – outis Nov 05 '21 at 20:39

4 Answers4

3

So, start by writing a generic pick function that takes an array and returns an item. I'll leave the implementation of that to you.

Next you need to use Object.keys to get an array like ['watch', 'read', 'play'].

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}
var keys = Object.keys(chooseOption);
var type = pick(keys);

Then you can get the inner array by accessing the property by that key.

var items = chooseOption[type];
var item = pick(items);

And finally, display the result.

console.log('You should ' + type + ' ' + item);
Brigand
  • 84,529
  • 20
  • 165
  • 173
  • Just a note: using Object.keys(chooseOption); doesn't guarantee the order in which the keys are returned. If order is important, you should base your chooseOption on an array instead of an object. – Lys Mar 30 '17 at 10:55
  • 1
    @Lys I would assume that order is not important here because the whole point is to select a property at random. – JLRishe Mar 30 '17 at 10:57
  • I agree, however I though it might be nice to mention it, just so @Timmster is aware, that there will be combination between the two random factors of random index and random order. – Lys Mar 30 '17 at 11:01
  • @Lys the order is guaranteed to be insertion order. There was a time where it wasn't in the spec, but all popular engines did this, so they added it. – Brigand Mar 30 '17 at 11:02
  • I would say the kid was asking for the Pick function.. lol – Rolando Niubó Mar 17 '21 at 14:30
1

Here is another solution using Math.random() to achieve randomness:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}


function getRandom(obj, item){
  // 1) select which property to operate on.
  var itemArr = obj[item];

  // 2) we already know that the key can only be an integer(between 0 and length -1 )

  // Math.random()   : to generate a random number(between [0-1]).
  // Math.round()    : to round a number to an integer.
  // number % length : to make sure the result would be an integer between 0 and length -1 
  var index = Math.round((Math.random() * itemArr.length)) % itemArr.length;


  return {
    property:itemArr,
    index: index,
    value: itemArr[index],
  }

}


console.log(getRandom(chooseOption,'watch'));
console.log(getRandom(chooseOption,'read'));
console.log(getRandom(chooseOption,'play'));
ismnoiet
  • 4,129
  • 24
  • 30
1

use with object.keys() and Math.random()

  1. first select the random key from object using Object.keys().length.
  2. Then get the respected array of the key.
  3. Then pick the random value from the array using array length

function newMovie() {
var types =Object.keys(chooseOption);
  var rn = Math.floor(Math.random() * (types.length));
var t = types[rn];
var val = chooseOption[types[rn]];
var vn = Math.floor(Math.random() * (val.length));
var v = val[vn]
 console.log("You should watch " +t +' '+v);
}

var chooseOption = {
  watch: ["star wars", "lotr", "moonlight", "avengers"],
  read: ["scott pilgrim", "harry potter", "eragon"],
  play: ["starbound", "skyrim", "bioshock", "fallout"]
}
newMovie()
prasanth
  • 22,145
  • 4
  • 29
  • 53
-1

Here you go,

    var options = {
        watch: ["star wars", "lotr", "moonlight", "avengers"],
        read: ["scott pilgrim", "harry potter", "eragon"],
        play: ["starbound", "skyrim", "bioshock", "fallout"]
    };

    for( i in options){
        //i is will be iterating with values "watch","read","play"
        t = Math.floor( Math.random()* options[i].length);
        //options[i] is to access the value of property eg: options["watch"]
        //will return ["star wars", "lotr", "moonlight", "avengers"]
        console.log("You should " + i +" "+ options[i][t]);
    }

Instead logging to something else with the code :)

not_python
  • 904
  • 6
  • 13