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?

2
  • Get a random number between 0 and chooseOption.length then do chooseOption.key(random number); Commented Mar 30, 2017 at 10:53
  • Does this answer your question? Pick random property from a Javascript object Commented Nov 5, 2021 at 20:39

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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 I would assume that order is not important here because the whole point is to select a property at random.
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 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.
I would say the kid was asking for the Pick function.. lol
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()

Comments

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'));

Comments

-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 :)

1 Comment

the for loop is not random

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.