Randomize Users in a Voice Channel (discord.js v12)

Viewed 92

I am trying to randomize users into two teams, team 1 and team 2. However, in some scenarios it repeats the same user on both teams.

For example:

Team 1: User 1

Team 2: User 1

  • The same user would be present on both teams instead of the other users' in the voice channel.

Is there a way to not present the same user twice or just once on one team.

try {
 
let users = message.member.voice.channel.members.map(member => `<@${member.user.id}>`)
                       
                        let team1 = users.sort(() => Math.random() - 0.5).slice(0, Math.floor(users.length / 2))
                        let team2 = users.sort(() => Math.random() - 0.5).slice(Math.floor(users.length / 2))
    
                        
                        const embed = new MessageEmbed()
                            .setTitle("Teams Created")
                            .setDescription(`Team 1: ${team1.join(', ')}\nTeam 2: ${team2.join(', ')}`)
                            .setColor("#36393E")
                            .setTimestamp()
                 
                        message.channel.send(embed)
                       
    
    
                    } catch (error) {
                        console.log(error)
                        const errorembed = new MessageEmbed()
                            .setTitle("⚙️ Error")
                            .setDescription(`An error has occured. Please try again`)
                            .setColor("#36393E")
                            .setFooter("If this error has occured multiple times, please contact the developer.")
                            .setTimestamp()
                        await message.channel.send("There was an error. Please try again.")
                    }
1 Answers

Once you have filled team1, you shouldn't users.sort() again, because once the first team is defined, the second one is also defined. If you sort again, you are giving the chance for that to happen. You just have to put in team2 the users that are not in team1.

let team2=users.filter(!(user=> team1.includes(user)));

I dont know right now if that line is correct, but it should be something like that.

Related