Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick 3 random elements from an array. And not get the same elements twice

Tags:

javascript

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(" , ");
    }
like image 278
Theskils Avatar asked Feb 13 '26 13:02

Theskils


1 Answers

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);
like image 72
guest271314 Avatar answered Feb 16 '26 02:02

guest271314