I want to create a 4 digit random word from this array.
const words = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'];
for that I coded like this..
const word = (
words[Math.floor(Math.random() * 9)] +
words[Math.floor(Math.random() * 9)] +
words[Math.floor(Math.random() * 9)] +
words[Math.floor(Math.random() * 9)]
);
console.log(word) // afab
For this I need to repeat the code words[Math.floor(Math.random() * 9)] again if I need 6 digit or 10 digit.
How can I write the code using a variable that is easy to generate N digit random words without repeat the code?
Thanks in advance
You can make use of Array.from and get the word of length length
Array.from({ length }, () => arr[Math.floor(Math.random() * arr.length)]).join("")
Create a dynamic length using
arr.length // instead of 9(Don't hardcode)
const words = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "k"];
function generateRandomWord(arr, length) {
return Array
.from({ length },() => arr[Math.floor(Math.random() * arr.length)])
.join("");
}
console.log(generateRandomWord(words, 4));
console.log(generateRandomWord(words, 8));
console.log(generateRandomWord(words, 12));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With