3

I'm writing a Discord bot. I have an Array called team, I wish to assign a user randomly a team. Once that user is assigned I want to assign the next user a team.

var teams = ["1","1","1","1","1","2","2","2","2","2"];
var heroes = ["a","b","c","d"...etc];

 for (var i = 0; i < 10; i++) {
        var randomHero = Math.floor(Math.random()*heroes.length)
        var randomTeam = Math.floor(Math.random()*teams.length)
        var hero = heroes[randomHero];
        heroes.splice(randomHero)
        var team = teams[randomTeam];
        message.channel.sendMessage(teams);
        teams.splice(randomTeam)
        message.channel.sendMessage(teams);
        message.channel.sendMessage(users[i] + " - " + hero + ' Team ' + team);
        }
    }

But I'm unsure how to make each person get a team, then remove that element. It keeps coming up with undefined.

Essentially I want the output to be like

Person 1 - a - Team 1 Person 2 - b - Team 2 Person 3 - e - Team 2

All the way until Person 10, where all the heroes are unique and all the teams are divided equally, 5 on team 1 5 on team 2!

Flimzy
  • 68,325
  • 15
  • 126
  • 165
TheRapture87
  • 1,313
  • 3
  • 15
  • 30

1 Answers1

1

You could use Array#splice with the second parameter 1 for one item as deleteCount and move the spliced value to the variable.

var teams = ["1", "1", "1", "1", "1", "2", "2", "2", "2", "2"],
    heroes = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
    randomHero, randomTeam, hero, team;

for (var i = 0; i < 10; i++) {
    randomHero = Math.floor(Math.random() * heroes.length)
    randomTeam = Math.floor(Math.random() * teams.length)
    hero = heroes.splice(randomHero, 1)[0];
    //                   deleteCount / \\\ take from the array the first element
    team = teams.splice(randomTeam, 1)[0];
    console.log(hero + ' Team ' + team);
}
console.log(heroes);
console.log(teams);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358