How would I get a random array, if I am using multiple arrays from an object? [closed]

Ok, so I am new to Javascript. I have created an object with 3 separated arrays.

const messages = {
  message:[
   ["joke1","joke2","joke3"],
   ["tease1","tease2","tease3"],
   ["boost1","boost2","boost3"]
};

now I need to take a random message every time the user logs in. so for example:

 messages.message[0][2] or messages.message[2][0]

i cant get the second part of this code to work.

The first part was easy.

i was able to get the first random number from the array.
that is put into the variable chooseArray1

here is where I am struggling.

const secondIndex = messages.message[chooseArray1[Math.floor(Math.random() * messages.message[chooseArray1])];

now Im getting an error here at the second [ in front of Math
I cant seem to figure out how to get the random number of an array with an index.

I hope this makes sense. Apparently I have the coding skill of a rock.

  • Does this answer your question? Getting a random value from a JavaScript array

    – 

  • I apologize, but this answer is for a single array. I am trying to access one of 3 arrays randomly, and then, access an index of that random array. total of 3 arrays, with 3 items in each.

    – 

  • Assuming that chooseArray1 is an actual array (so it’s something like const chooseArray1 = messages.message[Math.floor(Math.random() * messages.message.length)];), const secondIndex = Math.floor(Math.random() * chooseArray1.length); is what you’re looking for. Then you can run a console.log(chooseArray1[secondIndex]); to actually see the selected string in the console. But these are just guesses from the names, like chooseArray1 may be an array, while secondIndex is more likely a number.

    – 

The problem is that you are not using the length of the choosen array but the whole array itself.

Also, your syntax to select the second dimension is wrong.

Here’s the solution to your problem

const secondIndex = messages.message[chooseArray1][Math.floor(Math.random() * messages.message[chooseArray1].length)];

Also, note that the variable secondIndex contains the text to display and not the actual index. To only get the index, you can use:

Math.floor(Math.random() * messages.message[chooseArray1].length)

You can make a function to select a random array element and then use it twice — first to select one of the inner arrays, then to select one of the strings in that array:

Code in Playground

/** @type {<T>(array: ReadonlyArray<T>) => T} */
function getRandomElement(array) {
  return array[Math.floor(Math.random() * array.length)];
}

const messages = {
  message: [
    ["joke1", "joke2", "joke3"],
    ["tease1", "tease2", "tease3"],
    ["boost1", "boost2", "boost3"],
  ],
};

// One of the strings from one of the arrays in the array at messages.message:
const randomString = getRandomElement(getRandomElement(messages.message));

console.log(randomString);

Leave a Comment