Team sorting via a custom command

I am trying to find a way to sort the players on a team named “Pending” to one of four empty teams (named “A”,”B”,”C” and “D”) by running a command in chat. It should fill up each team equally and balanced.

Unfortunately after searching around on the dev forum and the internet, little to no help has come my way.

I found a method of sorting 2 teams, however this proved unsuccessful when going for 4 teams, and using it with a command.

Any help would be appreciated.

I won’t give you a script since that’s not really allowed on the devforum, but here’s my take on it:

After running the command, grab all the people in the Pending team and add them to some table. Divide the number of players to be assigned by 4 (the number of teams) and round that number down to the nearest integer. This is the number of people to put in each team, so assign this to a variable. Assign that many players to each team and we’re almost done. (Remember to remove them from the table after being assigned to a team!)
If the number of players originally in the Pending team couldn’t be divided equally into the four teams, there’ll be 1, 2 or 3 players left in your table (never more than 3), so just assign each to a random team and we’re done!

You could make a for loop that runs iterating through all the lists, after that the loop will get the lowest by setting a variable and then checking if the variable is higher than the number of members there is in the team, if that is the case it will set the variable. After you find the team with the lowest number of players, assign the person there and then repeat for all the players that need to be assigned