skip to Main Content

I got this code off here. It selects one of the names at random. All I need is to select more than one name but not repeat any

var textArray = [
  "Hello I'm Fred1",
  "Hello I'm Jimmy1",
  "Hello I'm Terry1",
  "Hello I'm Fred2",
  "Hello I'm Jimmy2",
  "Hello I'm Terry2",
  "Hello I'm Fred3",
  "Hello I'm Jimmy3",
  "Hello I'm Terry3"
];
var randomNumber = Math.floor(Math.random() * textArray.length); 
document.getElementById("randomNumber").innerHTML = textArray[randomNumber];
  <p id="randomNumber"> </p>

I can’t figure it out

2

Answers


  1. Just randomly splice from the array’s shallow copy:

    var textArray = [
      "Hello I'm Fred1",
      "Hello I'm Jimmy1",
      "Hello I'm Terry1",
      "Hello I'm Fred2",
      "Hello I'm Jimmy2",
      "Hello I'm Terry2",
      "Hello I'm Fred3",
      "Hello I'm Jimmy3",
      "Hello I'm Terry3"
    ];
    
    
    const copy = textArray.slice();
    const result = Array.from({length:5}, () => copy.splice(Math.random() * copy.length | 0, 1)[0]);
    
    document.getElementById('demo').innerHTML = result.join('<br/>')
    <p id="demo"></p>
    Login or Signup to reply.
  2. One way to do it:

    Generate three random indices for selecting lines.

    Select the lines at the random indices

    Join the selected lines into a single string with line breaks

    var textArray = [
      "Hello I'm Fred1",
      "Hello I'm Jimmy1",
      "Hello I'm Terry1",
      "Hello I'm Fred2",
      "Hello I'm Jimmy2",
      "Hello I'm Terry2",
      "Hello I'm Fred3",
      "Hello I'm Jimmy3",
      "Hello I'm Terry3"
    ];
    
    var randomIndices = [];
    while (randomIndices.length < 3) {
      var randomIndex = Math.floor(Math.random() * textArray.length);
      if (!randomIndices.includes(randomIndex)) {
        randomIndices.push(randomIndex);
      }
    }
    
    var selectedLines = randomIndices.map(index => textArray[index]);
    var output = selectedLines.join("<br>");
    
    document.getElementById("randomNumber").innerHTML = output;
    <p id="randomNumber"></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search