Pick 5 random letters from array

553 views javascript
5

For school I need to make a script that prints 3 times something with 5 random letters. "ajshw kcmal idksj"

I have made this:

var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 
'z'];

var random = myArray[Math.floor(Math.random() * myArray.length)];
document.write('<br>' +  random);

But this only prints one letter. How can it print 5 letters 3 times?

answered question

Your myArray[Math.floor(Math.random() * myArray.length)]; code is the key to get a random element from the array. You know functions? You could create a function that executes that code and then you could build another one to build a "word", which means running your random function 5 times. Then you can execute the "word" function 3 times and you're done :)

3 Answers

4

a simple way would be to simply generate that single letter multiple times with a loop. a way to do this would go as follows:

var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 
'z'];

var phrase = "";
for (var x = 0; x < 3; x++) {
    for (var y = 0; y < 5; y++) {
        phrase = phrase + myArray[Math.floor(Math.random() * myArray.length)];
    }
    phrase = phrase + " ";
}
console.log(phrase)

posted this
11

What about just making a nested loop:

const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 
'z'];

const length = myArray.length;

const numStrings = 3;
const numLetters = 5;

for (let i = 0; i < numStrings; i++) {
    let string = "";

    for (let j = 0; j < numLetters; j++) {
        let letter = myArray[Math.floor(Math.random() * length)];
        string += letter;
    }

    console.log(string);
}

posted this
1

Iterate 5 times to generate each word with 5 letters and iterate 3 times to generate three words. You can use for loop to generate the words or you can use array#map to generate the words and using array#join you can join them.

var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
    random = [...Array(3)]
      .map(_ => [...Array(5)].map(_ => myArray[Math.floor(Math.random() * myArray.length)]).join(''))
      .join('<br>');
document.write(random);

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories