How to Randomly Split Members into Groups in React
To split members randomly into groups, shuffle the roster once, then deal members one by one into group 1, 2, 3, and so on. This way, every group differs in size by at most one person. In a React component, don't calculate the split during rendering. Create it only when the button is pressed and store it in state. If you use random numbers during rendering, the groups will change every time you type a single character.
Here I built a GroupMaker component with a textarea for members, one per line, and a choice between "number of groups" and "members per group".
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, converted them with esbuild, and operated a development build wrapped in StrictMode with Playwright. To make the button-based version give the same result every time when operated with Playwright, I replaced Math.random with a random function with a fixed seed. I did not test Firefox, Safari, smartphones, or screen reader announcements. I did not add conditional splitting such as "don't put the same people together as last time."

Shuffling and then dealing in turn keeps sizes within one person
I put the grouping functions in a file that does not depend on React.
// Member grouping. Only plain functions that do not depend on React
// One member per line. Trims surrounding whitespace, removes empty lines and repeated names after the first
export function parseMembers(text: string): string[] {
const names = text.split('\n').map((line) => line.trim()).filter((name) => name !== '');
return [...new Set(names)];
}
// Returns a new array with the items reordered (Fisher–Yates shuffle)
export function shuffle<T>(items: readonly T[], rand: () => number = Math.random): T[] {
const a = [...items];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(rand() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
// Deals items into count groups so that sizes differ by at most one
export function splitIntoGroups<T>(items: readonly T[], count: number, rand: () => number = Math.random): T[][] {
const groups: T[][] = Array.from({ length: count }, () => []);
shuffle(items, rand).forEach((item, i) => {
groups[i % count].push(item);
});
return groups;
}
// Decides the number of groups from the maximum size of each group
export function countForSize(total: number, size: number): number {
return Math.ceil(total / size);
}
parseMembers turns the text in the textarea into an array of names. It uses trim() to remove surrounding whitespace, removes empty lines, and then puts the names into a Set to merge duplicates. In the test environment, passing " ねこ \n\nいぬ\nねこ\n \nうさぎ\n" returned ["ねこ","いぬ","うさぎ"]. A line containing only a full-width space was also removed as an empty line.
splitIntoGroups shuffles the roster with the Fisher–Yates method, then puts each member into group i % count in turn. When 10 people are split into 3 groups, the sizes are 4, 3, and 3. Because the dealing order is fixed, the larger groups always come first (11 people into 3 groups gave 4, 4, and 3).
When splitting by "members per group," countForSize first decides the number of groups, and then the same function deals the members. When 10 people are split with a maximum of 4 per group, the number of groups is Math.ceil(10 / 4), which is 3, and the sizes are 4, 3, and 3. Cutting the roster into chunks of 4 from the top would give 4, 4, and 2, so this method produces more even sizes. Results in the test environment were as follows:
| Members | Members per group (max) | Number of groups | Size of each group |
|---|---|---|---|
| 10 | 4 | 3 | 4, 3, 3 |
| 9 | 4 | 3 | 3, 3, 3 |
| 7 | 3 | 3 | 3, 2, 2 |
When 9 people are split with a maximum of 4 per group, no group of 4 is formed, and all groups have 3 people. "4 people max" is an upper limit, not a guarantee that every group has 4.
I tested 5,050 cases, covering 1 to 100 people split into 1 to 100 groups (no more groups than people). In every case, each person appeared exactly once and the size difference was at most one. I also tested 891 cases of 2 to 100 people split with a maximum of 2 to 10 per group. No group exceeded the maximum, and removing one group from the result would always have pushed some group over the maximum.
Choosing a group for each person one at a time leaves sizes uneven
For a purely random split, you could pick a group for each person with Math.floor(Math.random() * count). However, this approach does not keep sizes even. In the test environment, I split six people (A to F) into two groups 240,000 times. The size combinations were as follows:
3対3: 75058 / 4対2: 56318 / 2対4: 56148 / 5対1: 22708 / 1対5: 22424 / 6対0: 3711 / 0対6: 3633
The split into 3 and 3 happened 75,058 times, less than one third of the total. In another 7,344 cases, all six people ended up in one group.
When I split 240,000 times with splitIntoGroups, the result was always 3 and 3. Each of the 20 possible ways to choose 3 of the 6 people for group 1 appeared, and each occurred between 11,887 and 12,153 times. With no bias, each combination would occur about 12,000 times, so these counts are nearly equal. A and B ended up in the same group 95,998 times, and A and F 96,183 times. Both are close to the expected 96,000 (two out of five).
Writing the shuffle as sort(() => Math.random() - 0.5) produces a biased order. I checked this bias against Fisher–Yates in my earlier article, "How to Make a Card-Flipping Memory Game in React," so this article uses only Fisher–Yates.
Store the result in state when the button is pressed
For comparison, I also built a version that calculates the groups on every render and uses the button only to toggle whether they are displayed.
import { useState } from 'react';
import { parseMembers, splitIntoGroups } from './groups';
// Version for comparison: the groups are calculated on every render
export function GroupMakerV1() {
const [text, setText] = useState('');
const [shown, setShown] = useState(false);
const members = parseMembers(text);
const groups = splitIntoGroups(members, 3);
return (
<div className="groups">
<textarea rows={8} value={text} onChange={(e) => setText(e.target.value)} />
<button type="button" onClick={() => setShown(true)}>
グループに分ける
</button>
{shown && (
<ol className="result">
{groups.map((group, i) => (
<li key={i}>
<h3>グループ {i + 1}</h3>
<ul>
{group.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
</li>
))}
</ol>
)}
</div>
);
}
After splitting 10 people with this version, every time I typed a space at the end of the members field, the group membership changed.
押した直後: ["グループ 1 たぬき・くま・ねこ・うさぎ","グループ 2 りす・ひつじ・いぬ","グループ 3 さる・しか・きつね"]
末尾に空白を足した 1 回目: ["グループ 1 うさぎ・くま・いぬ・さる","グループ 2 ひつじ・りす・きつね","グループ 3 しか・ねこ・たぬき"]
末尾に空白を足した 2 回目: ["グループ 1 いぬ・しか・たぬき・ひつじ","グループ 2 ねこ・くま・きつね","グループ 3 うさぎ・りす・さる"]
末尾に空白を足した 3 回目: ["グループ 1 いぬ・しか・りす・たぬき","グループ 2 ねこ・くま・ひつじ","グループ 3 うさぎ・さる・きつね"]
trim() removes the spaces, so the roster itself did not change. Even so, typing changes the state, which re-renders the component, and each render calls splitIntoGroups with a new random number. The React documentation on keeping components pure says that a component should return the same output for the same input, and that side effects, meaning changes to the outside world, usually belong in event handlers. Using random numbers during rendering breaks this rule.
So in the button-based version, I moved the grouping into the onClick handler of the button and stored the result in state.
import { useId, useState } from 'react';
import { countForSize, parseMembers, splitIntoGroups } from './groups';
type Mode = 'count' | 'size';
type Result = { key: string; groups: string[][] };
const NUMBERS = [2, 3, 4, 5, 6, 7, 8, 9, 10];
export function GroupMaker() {
const id = useId();
const [text, setText] = useState('');
const [mode, setMode] = useState<Mode>('count');
const [n, setN] = useState(2);
const [result, setResult] = useState<Result | null>(null);
const members = parseMembers(text);
const wanted = mode === 'count' ? n : countForSize(members.length, n);
const count = Math.min(wanted, members.length); // Do not create more groups than members
const key = JSON.stringify([members, count]);
const stale = result !== null && result.key !== key;
function handleSplit() {
setResult({ key, groups: splitIntoGroups(members, count) });
}
return (
<div className="groups">
<label htmlFor={`${id}-members`}>メンバー(1行に1人)</label>
<textarea id={`${id}-members`} rows={8} value={text} onChange={(e) => setText(e.target.value)} />
<p className="hint">{members.length} 人</p>
<fieldset>
<legend>分け方</legend>
<label>
<input type="radio" name={`${id}-mode`} checked={mode === 'count'} onChange={() => setMode('count')} />
グループの数を決める
</label>
<label>
<input type="radio" name={`${id}-mode`} checked={mode === 'size'} onChange={() => setMode('size')} />
1グループの人数を決める
</label>
</fieldset>
<label htmlFor={`${id}-n`}>{mode === 'count' ? 'グループの数' : '1グループの人数(最大)'}</label>
<select id={`${id}-n`} value={n} onChange={(e) => setN(Number(e.target.value))}>
{NUMBERS.map((v) => (
<option key={v} value={v}>
{mode === 'count' ? `${v} グループ` : `${v} 人まで`}
</option>
))}
</select>
<button type="button" disabled={members.length < 2} onClick={handleSplit}>
{result ? 'もう一度分ける' : 'グループに分ける'}
</button>
{stale && <p className="hint">メンバーか分け方が変わりました。ボタンを押すと分け直します。</p>}
{result && (
<ol className={stale ? 'result stale' : 'result'}>
{result.groups.map((group, i) => (
<li key={i}>
<h3>
グループ {i + 1}({group.length} 人)
</h3>
<ul>
{group.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
</li>
))}
</ol>
)}
</div>
);
}
.groups {
display: grid;
gap: 8px;
max-width: 420px;
}
.groups textarea {
font-size: 1rem;
}
.groups .hint {
margin: 0;
color: #555;
font-size: 0.875rem;
}
.groups fieldset {
display: grid;
gap: 4px;
}
.groups select,
.groups button {
font-size: 1rem;
min-height: 44px;
}
.groups .result {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 8px;
padding: 0;
list-style: none;
}
.groups .result > li {
padding: 8px;
border: 2px solid #00c8e8;
border-radius: 8px;
}
.groups .result h3 {
margin: 0 0 4px;
font-size: 0.875rem;
color: #067a98;
}
.groups .result ul {
margin: 0;
padding-left: 1.2em;
}
.groups .result.stale {
opacity: 0.4;
}
After splitting 10 people with "4 people max" in this version, adding a trailing space in the members field did not change the groups. Switching the split method to "number of groups" and back to "members per group" also left the result the same.
The number of members and the number of groups derived from it are not stored in state. They are calculated on every render. The same roster string always produces the same values, so calculating them during rendering is safe. Only the result, which is decided when the button is pressed, goes into state.
When the members change, fade out the previous result
Once the result is in state, adding members does not change the display until the button is pressed. So I stored the roster and the number of groups used to make the result, as a string in key (not the same as a list key), together with the result. When the current key differs from it, the result is shown faded and the message "The members or the split method has changed. Press the button to split again." appears.
In the test environment, after splitting 10 people, I added an 11th member named "Koala". The member count changed to 11, the message appeared, and the ol for the result received the stale class. The group membership stayed the same. Pressing the button again split the 11 people into 4, 4, and 3, and the message disappeared.
When there are 0 or 1 members, the button is disabled. The number of groups never exceeds the number of members, so splitting 3 people into "5 groups" produced three groups of one person each. Since parseMembers ensures that names do not repeat within the groups, I used each name directly as the list key.





