How to get random characters from multiple different arrays in JavaScript

Viewed 39
const array1 = ["A", "b", "C", "D", "f"]
const array2 = ["❤️", "", "", "", ""]
const array3 = ["0", "1", "2", "3", "4", "5"]


function renderItem() {
    let randomI = Math.floor(Math.random() * array1.length)
    console.log(array2[randomI])
}


function generateRandom () {
    let randomValue = ""
    for(let i = 0; i < 4; i++) {
        randomValue += renderItem()
    }
    return randomValue
}

How do I generate random characters from all of the(3) arrays? and stitch them together.

1 Answers

maybe do a 2d array? if you don't want to change the original arrays.

const arr = [array1, array2, array3]
function renderItem() {
    //randomly select an array
    let randArrIndex= Math.floor(Math.random() * arr.length)
    //now select a random Item from that array (we need it's length to get a valid index)
    let randItemIndex = Math.floor(Math.random() * arr[randArrIndex].length)
    console.log(arr[randArrIndex][randItemIndex])
}

sorry if I didn't understand the question correctly

EDIT: if you want at least two characters from each array you can do this:

const array1 = ["A", "b", "C", "D", "f"];
const array2 = ["❤️", "", "", "", ""];
const array3 = ["0", "1", "2", "3", "4", "5"];
const arr = [array1, array2, array3];
const minimum = 2;
const arrCount = new Array(arr.length).fill(0);
function renderItem() {
  let randArrIndex;
  do {
    randArrIndex = Math.floor(Math.random() * arr.length);
    //get another index if this array already have the minimum number
    //and there is another array that still didn't reach the minimum
  } while (arrCount[randArrIndex] >= minimum && arrCount.some((e) => e < minimum));

  //increase the count for the selected array index
  arrCount[randArrIndex]++;

  //now select a random Item from that array (we need it's length to get a valid index)
  let randItemIndex = Math.floor(Math.random() * arr[randArrIndex].length);
  return arr[randArrIndex][randItemIndex];
}

function generateRandom() {
  let randomValue = "";
  //!! the string need to be at least equal to: minimum * arr.length
  // otherwise you will have an infinite loop
  for (let i = 0; i < 6; i++) {
    randomValue += renderItem();
  }
  return randomValue;
}
console.log(generateRandom());

basically just making sure at every random value that all your numbers have reached the minimum (2 characters) if not it will keep generating indexes

though this solution will make the result not entirely random as the string will surely have 2 characters from each array at the start of it. what you can do is shuffle the string after finishing to make sure it's completely random

Related