I have this array:
const participants = [
{id: 1, name: 'Tom', gender: 'm'}
,{id: 2, name: 'Paul', gender: 'm'}
,{id: 3, name: 'Igor', gender: 'm'}
,{id: 4, name: 'Anna', gender: 'f'}
,{id: 5, name: 'Mary', gender: 'f'}
,{id: 6, name: 'Alice', gender: 'f'}
];
Now, for each "round" I want to let each man be paired with a girl. Something like:
First round:
Tom and Anna
Paul and Mary
Igor and Alice
Second round:
Tom and Mary
Paul and Alice
Igor and Anna
Thirth round:
Tom and Alice
Paul and Anna
Igor and Mary
However, it could happen that there are only 2 girls (Anna and Mary). In that case, for each round, one of the guy should be "alone".
What is the best way to create an algorithm for that? I have created an algorithm that does not really do the job the right way, as the result is not following the scenario described above.
const participants = [
{ id: 1, name: 'Tom', gender: 'm' },
{ id: 2, name: 'Paul', gender: 'm' },
{ id: 3, name: 'Igor', gender: 'm' },
{ id: 4, name: 'Anna', gender: 'f' },
{ id: 5, name: 'Mary', gender: 'f' },
{ id: 6, name: 'Alice', gender: 'f' }
];
const men = participants.filter(el => el.gender === 'm');
const women = participants.filter(el => el.gender === 'f');
let currentIndex = 0;
let pairs = [];
men.forEach((el, index) => {
const tmpPair = [];
men.forEach((el2, index2) => {
let woman = null;
if ((index2 + currentIndex) >= women.length) {
woman = women[0];
} else {
woman = women[index2 + currentIndex];
}
tmpPair.push({ man: men[index2], woman: woman });
});
currentIndex++;
pairs.push(tmpPair);
});
console.log(pairs);