Search code examples
javascriptarrayssplice

How do you split up an odd number of people into X teams?


So I'm working on a function that splits up the contents of an array into different "teams":

    generateTeams(players, numTeams)
    {
        var tempArray = [];
        tempArray = players.slice();

        var arrayLength = tempArray.length;
        var playerPerTeam = 
        Math.floor(tempArray.length/numTeams);
        console.log("chunk size is:", playerPerTeam)
        var results = [];

        while (tempArray.length){
           console.log("length",tempArray.length)
           results.push(tempArray.splice(0, playerPerTeam));
        } 
    }

If I feed it this input:

players = ["Juan", "Jeff", "Derek", "Bob", "Elizabeth", "Alex", "Isabelle"]
numTeams = 3

the function returns this:

["Juan", "Jeff"] ["Derek", "Bob"]["Elizabeth", "Alex"] ["Isabelle"]

So it returns 4 teams instead of 3. I was expecting one team to have 3 players and the other 2 teams to have 2 players instead of it making a separate team.

There's probably a simple solution I'm missing but I've been looking at how to split up this array into a certain number of teams and I can't quite figure it out.

Any help would be appreciated!


Solution

  • function generateTeams(players, numTeams)
        {
            var tempArray = [];
            tempArray = players.slice();
    
            var arrayLength = tempArray.length;
            var playerPerTeam = 
            Math.floor(tempArray.length/numTeams);
            console.log("chunk size is:", playerPerTeam)
            var results = [];
            while (results.length < numTeams ){
               results.push(tempArray.splice(0, playerPerTeam));
            }
            if(tempArray.length){
            results[results.length-1]=[...results[results.length-1],...tempArray]
            }
            return results;
        }
    
    var players = ["Juan", "Jeff", "Derek", "Bob", "Elizabeth", "Alex", "Isabelle"];
    var players2 = ["Juan", "Jeff", "Derek"];
    var players3 =  ["Juan", "Jeff", "Derek", "Bob", "Elizabeth"]
    console.log(generateTeams(players,3));
    console.log(generateTeams(players2,3));
    console.log(generateTeams(players3,3))

    Make use of es6 array spread

    if you want playerPerTeam to have 3 uses Math.ceil instead