Javascript: Trying to randomly move items from one array to another

702 views Asked by At

I've been stuck for a couple hours now trying to randomly select one item from one array (players) to another (team1).

I've got it working by doing something else with splice, but unfortunately splice creates an array itself with the removed items and so I ended up getting an array with an array.

This is what I got so far:

var players = ["P1", "P2", "P3", "P4"];

var team1 = [];
var team2 = [];

var select = Math.floor(Math.random() * players.length);
var tmp;

if (team1.length < 2) {
  tmp.push(players.splice(select, 1));
  team1.push(tmp.pop);
}

console.log(team1);
console.log(tmp);
console.log(players);

If I'm doing this all wrong I'm sorry, still pretty new to this website, help is appreciated.

2

There are 2 answers

4
Saravanan I On BEST ANSWER

You just have to select the first element from the array while splicing and pushing to team,

var players = ["P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8"];

var team1 = [];
var team2 = [];

var tmp = [];
while (team1.length < 4) {
  tmp.push(players.splice(Math.floor(Math.random() * players.length - 1), 1)[0]);
  team1.push(tmp.pop());
}

while (team2.length < 4) {
  tmp.push(players.splice(Math.floor(Math.random() * players.length - 1), 1)[0]);
  team2.push(tmp.pop());
}

console.log(team1);
console.log(team2);
console.log(tmp);
console.log(players);
0
Ramesh Lamba On

you try like this in your scenario

var players = ["P1", "P2", "P3", "P4"];

var team1 = [];
var team2 = [];
var temp = players.slice();

for(i=0; i<temp.length; i++){
     var select = Math.floor(Math.random() * temp.length);
     console.log(select);
     if (team1.length <= temp.length/2) {
        team1.push(temp[select]);
      }
      temp.splice(select, 1);
}
team2 = temp.slice();

console.log('team 1 ---',team1);
console.log('team 2 ---',team2);
console.log('players ---', players);