Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create N digit random words from an array

Tags:

javascript

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

like image 753
Irfan Habib Avatar asked Dec 31 '25 17:12

Irfan Habib


1 Answers

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));
like image 189
decpk Avatar answered Jan 02 '26 10:01

decpk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!