JSFiddle - React, Tailwind, and code Playground

by SHELDON PASCIAK

JavaScript

function createGroups(students) {
  if (students.length % 4 !== 0) {
    console.error('The number of students must be a multiple of 4 for this to work.');
    return;
  }

  const numGroups = students.length / 4;
  const groups = new Array(numGroups).fill(null).map(() => []);
  let rotatedStudents = students.slice();

  for (let round = 1; round < students.length; round++) {
    for (let groupIndex = 0; groupIndex < numGroups; groupIndex++) {
      const student = rotatedStudents.pop();
      groups[groupIndex].push(student);
    }

    // Rotate students for the next round
    rotatedStudents = [rotatedStudents.pop()].concat(rotatedStudents);
  }

  return groups;
}

const students = ['Student1', 'Student2', 'Student3', 'Student4', 'Student5', 'Student6', 'Student7', 'Student8', 'Student9', 'Student10', 'Student11', 'Student12', 'Student13', 'Student14', 'Student15', 'Student16', 'Student17', 'Student18', 'Student19', 'Student20', 'Student21', 'Student22', 'Student23', 'Student24'];

const groups = createGroups(students);
console.log(groups);