Hán
Hán

Reputation: 1

Problem with Array elements and randomized in Javascript

Here is a pretty weird problem for me.

I have an array, like this: let rolescheck1 = [1, 2, 3, 4]

And then I want to randomly select an element from that Array, then I will remove it from that Array until there is no element left inside that Array:

                    let randomroles = Math.floor(Math.random() * rolescheck1.length);
                    console.log(rolescheck1[randomroles]);
                    var selectedrole = rolescheck1[randomroles];
                    rolescheck1 = rolescheck1.filter(function(item){
                        return item !== selectedrole
                    })

I put the randomly select part inside a for() function like this:

for(var i = 0; i <= rolescheck1.length; i++){
         //The code above
}

But then it returned: 1, 2, 3, 2

I tried [4, 3, 2, 1] it still returned 1, 2, 3, 2

Anyone have ideas about what's going on? Thank you for your help!

Here is the full code:

for (var i = 0; i <= rolescheck2; i++) {
  let randomroles = Math.floor(Math.random() * rolescheck1.length);
  console.log(rolescheck1[randomroles]);
  var selectedrole = rolescheck1[randomroles];
  rolescheck1 = rolescheck1.filter(function(item){
    return item !== selectedrole
  })
} 

Upvotes: 0

Views: 45

Answers (2)

Goutham
Goutham

Reputation: 305

This should work

let rolescheck1 = [1, 2, 3, 4];

let rolescheck2 = [...rolescheck1];

while (rolescheck2.length !== 0) {
   const randomroles = Math.floor(Math.random() * rolescheck1.length);
   const selectedrole = rolescheck1[randomroles];
   rolescheck2 = rolescheck2.filter((role) => role !== selectedrole);
}
console.log('rolescheck2', rolescheck2); // []

Upvotes: 0

Serhan Yav&#231;in
Serhan Yav&#231;in

Reputation: 89

Maybe this can solve your problem.

var orginal = [1,2,3,4];
var copy = [1,2,3,4];

function getRandomElement(){
   var idx = Math.floor(Math.random()*copy.length);
   var element = copy[idx];
   copy.splice(idx,1);
   return element;
}


for(i = 0;i<orginal.length;i++){
 let element = getRandomElement();
}

The first array is your original data. If it is the second array, give a copy. If you delete an element from the copy data in each loop, you will always get a different value.

Upvotes: 1

Related Questions