I want to chunk an array into groups with the last few groups having the biggest size if the array cannot be divided evenly. Like the Euro Cup 2024 qualifiers where there are 53 teams divided into 10 groups with the last few groups having the biggest size (5x5x5x5x5x5x5x6x6x6). Here’s the code to chunk the array but it has the first few groups with biggest size [Fiddle] (6x6x6x5x5x5x5x5x5x5):
function partition(arr: Team[], group: number) {
let rest = arr.length % group;
let size = Math.floor(arr.length / group);
let j = 0;
return Array.from({ length: group }, (_, i) => {
return arr.slice(j, (j += size + (i < rest ? 1 : 0)));
});
}
let data = Array.from({length: 53}, (_,i) => i+1);
let result = partition(data, 10);
// result.reverse() is not ideal and would complicate things.
console.log(result);
Using reverse()
to flip the result is not ideal in my case because some teams from the arr
must be the first few groups. Ifreverse
is used, these teams would be placed in the last few groups. Is there a way to chunk the array into something like this (5x5x5x5x5x5x5x6x6x6)?
4
Answers
try the following add the extra members to the end of the group
working example
Here’s an approach that just splices off groups from the input array, and uses the current index to determine whether an additional team needs to be added to a group.
Playground link.
This prevents you from having to keep track of the current index in a variable outside of the callback function. It does modify the input array, so if that is an issue, you’d probably want to copy the array (e.g.
const data = [...teams];
) first.You need just a small fix here, instead of
i < rest
dogroup - i <= rest
(to make groups bigger in the end of the group array):