Good morning. I am making a code in javascript, to split an array of names into groups. It is just an example, but I will use it in a football system that I participate in.
I want to do everything dynamically, but let's break it down: I have this code, which divides by teams (I used the name of medications because I already had a list here), and I wanted it to be divided by a defined number (4 teams of 6 participants). But it is generating an object with 2 arrays of 5 names, and 3 arrays of 4 names.
Could you help me make the code generate 3 teams of 6 participants, and the last team of 4 participants?
var array = ['TRAXONOL 100MG',
'CETOMICOSS 200MG',
'CETONEO 200MG',
'UROVIT 100MG',
'UROVIT 100MG',
'UNI VIR 200MG',
'AFTILIV',
'LEIBA SACHE',
'LEIBA CAPS',
'SUPOSITORIO GLICERINA',
'GLICERIN',
'SEAKALM LIQUIDO',
'SEAKALM COMP',
'VERTIGIUM 10MG',
'FLUCANIL 150MG',
'TENSALIV 10MG',
'FONT D GTS',
'VITACIN 1G',
'CENEVIT 1G',
'TONICO VITAL',
'NUTRI HOMEM',
'NUTRI MAIS LIQUIDO'
];
function distributePlayers(names, numberOfTeams) {
var ret = {};
var teamCounter = 0;
for (var i = 0; i < names.length; ++i) {
if (!ret["array" + teamCounter]) {
ret["array" + teamCounter] = [];
}
ret["array" + teamCounter].push(names[i]);
if (++teamCounter == numberOfTeams) {
teamCounter = 0;
}
}
return ret;
}
var arrays = distributePlayers(array, 4);
console.log(arrays)
Example here: link
Thank you!