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!

2
  • What is coming up as undefined? Commented Nov 23, 2016 at 18:18
  • Your splice is deleting everything from the current index on wards. Add "1" after, to say you only want to delete 1. Commented Nov 23, 2016 at 18:26

1 Answer 1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.