DEV Community

Ave Mujica Technology
Ave Mujica Technology

Posted on

Shuffle once, then deal: making balanced teams in JavaScript

If you assign seven people to three teams by rolling a die for each person, the teams can end up with four, two, and one member. For a workshop, the useful guarantee is simple: team sizes differ by at most one.

Shuffle the list first

In a small browser-based grouping tool, I read one name per line, trim whitespace, and drop blank lines. I check that the number of teams is an integer between one and the number of participants. Then I shuffle the entries with Fisher–Yates, choosing a random position from zero through the current index at each step. Identical display names still represent separate entries.

Deal one name to each team in turn

function splitIntoGroups(shuffled, groupCount) {
  const groups = Array.from({ length: groupCount }, () => []);
  shuffled.forEach((name, index) => {
    groups[index % groupCount].push(name);
  });
  return groups;
}
Enter fullscreen mode Exit fullscreen mode

Given the already shuffled order [E, F, A, D, G, B, C], the result is [E, D, C], [F, G], and [A, B]. I checked the same seven-person, three-team case in the browser. Each full pass through the list of teams gives every team one person. The final partial pass can add at most one extra person per team.

Keep input and output on the page

The tool runs the draw on the current page and puts the result on screen before offering a copy button. If the browser rejects clipboard access, the visible result still gives people something they can select and copy. Reloading clears the pasted list.

This covers headcount. If you need to spread mentors across teams or keep pairs together, those constraints need their own assignment step.

Disclosure: AI assisted with drafting this article. The grouping behavior was checked against the working browser example.

Top comments (0)