I am trying to get this function to print out three random names without using the same name twice. I started trying with an If inside the for-loop, but have no idea if that is correct. Appriciate all help as i feel kinda stuck at this point in learning Javascript.
var name = ["Kai", "Lars", "Anders", "Ole", "Petter", "Mikael", "Cos", "Sin"];
var randName = [];
function randomNavn(){
document.getElementById("utskrift").innerHTML = "";
for( i = 0; i < 3; i++){
randName.push(name.splice(Math.floor(Math.random() * name.length), 1));
if(name[i] === randName[i]){
}
}
document.getElementById("utskrift").innerHTML = randName.join(" , ");
}
You can use do..while loop. Note also [0] at close of .splice() to return value of array instead of array.
var names = ["Kai", "Lars", "Anders", "Ole"
, "Petter", "Mikael", "Cos", "Sin"];
var randName = [];
do {
randName[randName.length] = names.splice(
Math.floor(Math.random() * names.length)
, 1)[0];
} while (randName.length < 3);
console.log(randName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With