1
Good morning. I’m making code in javascript, to divide an array of names into groups. It’s just an example, but I’ll use it in a system for football.
I want to do everything dynamically, but let’s go in parts: I have this code, which divides by teams (I used the name of medicines because I already had a list here), and I wanted it to be divided by defined number (4 teams of 6 participants). Only it is generating an Object with 2 arrays of 5 names, and 3 arrays of 4 names.
They could 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: http://jsfiddle.net/guilhermelirio85/0djLyg9p/
Thank you!
Perfect! Thank you and I will study the code better!
– Guilherme Lirio
That one
==
instead of>=
ai in the comparison of the end - will not give problem when the division ofnames.length / numberOfTeams
not whole?– jsbueno
Javascript has no entire division.
Math.ceil()
always returns an integer.– Glorfindel