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));
function recursiveRandomWord(words, len) {
if (len == 0) {
return '';
}
return words[Math.floor(Math.random() * words.length)] + recursiveRandomWord(words, len - 1);
}
const words = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'];
for (let i = 0; i < 10; i++) {
let length = Math.floor(Math.random() * 5) + 4;
console.log(`Length ${length}, Word: ${recursiveRandomWord(words, length)}`);
}
const words = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'];
function randomWord(arr, len) {
let result = [];
for (let i = 0; i < len; i++) {
result.push(
words[
Math.floor(Math.random() * words.length)
]
);
}
return result.join('');
}
for (let i = 0; i < 10; i++) {
let length = Math.floor(Math.random() * 5) + 4;
console.log(`Length ${length}, Word: ${randomWord(words, length)}`);
}
Note: Will work in older browser for eg: Internet Explorer 6
This is a functional approach. First call you pass the target array to choose items from, then the next call is the amount.
const numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
const words = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'];
function randomNum(target) {
const newRandomNum = (num = 1, val = "") => {
val += (target[Math.floor(Math.random() * 9)])
if (num === 1) return val;
return newRandomNum(--num, val);
}
return newRandomNum;
}
console.log(randomNum(numbers)(5));
console.log(randomNum(numbers)(10));
console.log(randomNum(words)(5));
console.log(randomNum(words)(10));
An improvement you could make is to check the type of the target array, then use += for strings, and another method for numbers since you don't want to add them.