Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
Multiple loop generate error for different entries

I made this function to generate custom fixture, but i have an issue if the players in rounds are more than 8. I tried to add 10 playes instead of 8, and the loop return me a wrong result.

let teams = [
  { id: "Team1" },
  { id: "Team2" },
  { id: "Team3" },
  { id: "Team4" },
  { id: "Team5" },
  { id: "Team6" },
  { id: "Team7" },
  { id: "Team8" },
  {id: "Team9" },
  {id: "Team10" }               
]

// Total rounds
let totRounds = 3
// Array with rounds
let rounds = []

for (let i = 0; i < totRounds; i++) {

  // This loop add an array on enemyes teams enemies["team2,..."]
  teams.forEach(team => team.enemies = teams.filter(enemy => enemy !== team));
  // Empty Array for first round 
  const matches = [];
  // Empty Array for second round ( return )
  const matches_return = [];

  while (teams.some(team => team.enemies.length)) {

    const playing = [];
    const playing_return = []
    for (const team of teams) {
      //debugger
      if (playing.includes(team)) continue;
      const enemy = team.enemies.find(enemy => !playing.includes(enemy));
      if (!enemy) continue;

      team.enemies.splice(team.enemies.indexOf(enemy), 1);
      enemy.enemies.splice(enemy.enemies.indexOf(team), 1);

      playing.push(team, enemy);
      playing_return.push(enemy, team);
    }

    if (playing.length) matches.push(playing.map(t => t.id))
    if (playing_return.length) matches_return.push(playing_return.map(t => t.id))
  }

  // Merge 2 arrays
  const totalMatches = matches.concat(matches_return)
  rounds.push(totalMatches);

}
console.log(rounds);

This work with 8 players, but with 10 or more not. I tried to made some changes but they didn't work.

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!