Ad

Random Item From The Array Without Repeating Elements In Javascript

- 1 answer

I don't want the function to repeat elements taken from the array

function Gen() {
    let Qu = ["Yazeed", "Ammar", "Marwan", "Othman", "Sameh", "Amro", "Ibraheem"];
    let p1 = document.getElementById("demo1");
    let text = " ";
    for (let i = 0; i < 4; i++) {  //Qu.length = 7
            let p = Qu[Math.floor(Math.random() * Qu.length)];
            text+= "This is " + p  + "<br>";
    }
    p1.innerHTML = text;
}
Ad

Answer

You can use splice to remove the item from the array after displaying it.

If you don't want to alter the array, then you can create a copy before altering it.

let id = Math.floor(Math.random() * Qu.length);
let p = Qu[id];
Qu.splice(id, 1);
text += "This is " + p + "<br>";

Working code:

function Gen() {
  let Qu = ["Yazeed", "Ammar", "Marwan", "Othman", "Sameh", "Amro", "Ibraheem"];
  let p1 = document.getElementById("demo1");
  let text = " ";
  for (let i = 0; i < 4; i++) { //Qu.length = 7
    let id = Math.floor(Math.random() * Qu.length);
    let p = Qu[id];
    Qu.splice(id, 1);
    text += "This is " + p + "<br>";
  }
  p1.innerHTML = text;
}
<div id="demo1"></div>
<button type="button" onclick="Gen()">Generate</button>

Ad
source: stackoverflow.com
Ad