Home > Blockchain >  How do I use a loop to pick random characters from an array
How do I use a loop to pick random characters from an array

Time:01-19

So I am working on a password generator and I have an array of possible characters, populated from user choices. I am trying to get random characters from the array the length of the users chosen password length, but it is only returning one character. Can anyone tell me what I'm doing wrong please?


// function to prompt user for desired password length
function getLength() {
  let passwordLength = prompt("Pick a length between 10 and 64 characters");
  let passwordLengthValue = passwordLength.valueOf();
  if (passwordLength >= 10 && passwordLength <= 64) {
    return passwordLengthValue;
  } else if (passwordLength < 10 || passwordLength > 64) {
    alert("You must pick a value between 10 and 64");
  }
  if (confirm("do you want to try again")){
    return getLength();
  }
  }

var passwordBase = [];

// Function to prompt user for password options
function getCharacterTypes() {


  if (confirm("Do you want lowercase characters?")) {
    passwordBase = passwordBase.concat(lowerCasedCharacters)
  };
  if (confirm("Do you want uppercase characters?")) {
    passwordBase = passwordBase.concat(upperCasedCharacters)
  };
  if (confirm("Do you want numbers?")) {
    passwordBase = passwordBase.concat(numericCharacters)
  };
  if (confirm("Do you want special characters")) {
    passwordBase = passwordBase.concat(specialCharacters)
  };

  if (passwordBase.length > 0) {

    return passwordBase;

  } else {
    (confirm("do you want to try again"))

    return getCharacterTypes()

  };

}

var characterTotal = getLength();
  var randomCharacter = []

  // Function for getting a random element from an array
function getRandom(passwordBase) {

  for (i = 0; i < characterTotal.length; i  ) {

  randomCharacter = passwordBase[Math.floor(Math.random() * passwordBase.length)];

    return randomCharacter;
  }
};

I have tried passing different arrays into the getRandom() function, and I tried it without the for loop but get the same single character result.

CodePudding user response:

The way your function is written, you are replacing the variable randomCharacter in each iteration of the loop. What you need to do is to add the random character that you're trying to get from the passworBase to the array that you have defined.

// Function for getting a random element from an array
function getRandom(passwordBase) {

    for (i = 0; i < characterTotal.length; i  ) {
        randomCharacter.push(passwordBase[Math.floor(Math.random() * passwordBase.length)]);
    }
    return randomCharacter;
};

CodePudding user response:

Zgjim's answer points out a good note in your code, I have something similar that you might find value in though it's not an exact answer to your code. It's a variation of how to accomplish this, though I incorporated html for selecting size / content of the password generated. Hopefully you find value in it!

const $ = str => [...document.querySelectorAll(str)];
const passEl = $("#pass-len")[0];
const optionEls = $("input.options");
const generate = $("#generate")[0];
const display = $("#display")[0];

const charLookup = {
  lowercase: "abcdefghijklmnopqrstuvwxyz",
  uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  numbers: "1234567890",
  special: "!@#$%^&*()"
};

// Function for getting a random element from an array
function generatePassword() {
  const len = passEl.value;
  const options = optionEls.filter(el => el.checked).map(el => el.value);
  const charStr = options.reduce((a,b) => a   charLookup[b], "");
  const avaliableChars = [...charStr];
  const max = avaliableChars.length;

  let password = "";
  for (let i = 0; i < len; i  ) {
    const randomIndex = Math.floor(Math.random() * max);
    password  = avaliableChars[randomIndex];
  }
  return password;
}

generate.addEventListener("click", () => {
  const pass = generatePassword();
  display.innerText = pass;
});
body {
  background-color: lavender;
}

label {
  user-select: none;
  outline: 1px solid black;
}

label:hover {
  outline: 1px solid lightgreen;
}
password length: <input id="pass-len" type="range" min="10" max="64" /> <br />
options:
<label>lowercase <input value="lowercase"  type="checkbox"></label>
<label>uppercase <input value="uppercase"  type="checkbox"></label>
<label>numbers <input value="numbers"  type="checkbox"></label>
<label>special characters <input value="special"  type="checkbox"></label> <br />
<button id="generate">generate</button>
<span id="display"></span>

Just as a note, Math.random should not be used as a password generator in production because it is not safe. There are libraries that exist for password generation and are more secure, if that interests you! Good luck

  • Related