Home > Back-end >  Split and array in 2 arrays
Split and array in 2 arrays

Time:09-22

need your help. Trying to separate the playersArr into 2 arrays. Tried everything but i think my inputs and/or are missing something. Need some guidance. Thank you [1]: https://i.stack.imgur.com/Gz3M3.jpg

My code:

function newPlayer() {

  const newPlayer = document.createElement('li')
  newPlayer.innerText = addPlayer.value
  newPlayer.classList.add('player')
  players.appendChild(newPlayer)

  const trashButton = document.createElement('button');
  trashButton.innerHTML = '<i ></i>';
  trashButton.classList.add('fa')
  newPlayer.appendChild(trashButton)

  playersArr.push(document.getElementById("input").value);

}
btnAddPlayer.addEventListener('click', newPlayer)


const nrTeams = 2
const player = document.querySelectorAll('player')
const genBtn = document.getElementById('gen-btn')


let teams = [];

const getTeams = () => {

  // Split the players array into set amount of teams.

  while (playersArr.length) {
    const teamSize = Math.ceil(playersArr.length / 2);
    const team = playersArr.slice(0, teamSize);
    teams.push(team);
    playersArr = playersArr.slice(teamSize);
  }
}

genBtn.addEventListener('click', getTeams())

CodePudding user response:

the idea is to create chunk from array with your team member

with

  • a for loop (to get only max number of player)
  • slice method (to get one chunk)

you can use slice method to create a chunk of your array with maximum size of team size

   const getTeams = () => {
      const teamSize = Math.ceil(playersArr.length / nrTeams);
      for (let i = 0; i < playersArr.length; i  = teamSize) {
        const team = playersArr.slice(i, i   teamSize);
        teams.push(team);
      }
    }
 

const teams = [];
const nrTeams = 2;
const playersArr = [
  'player1',
  'player2',
  'player3',
  'player4',
  'player5',
];

const getTeams = () => {
  const teamSize = Math.ceil(playersArr.length / nrTeams);
  for (let i = 0; i < playersArr.length; i  = teamSize) {
    const team = playersArr.slice(i, i   teamSize);
    teams.push(team);
  }
}

getTeams();
console.log(teams);

CodePudding user response:

You can split them evenly with a filter and modulus operation:

let players = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let teams = [
  players.filter((_n, i) => i % 2 === 0),
  players.filter((_n, i) => i % 2 !== 0)
];
console.log(teams);

CodePudding user response:

jeremy-denis Answered it very well, anyway if you need to ignore the for loop since you are using 2 teams, suppose teamOne and teamTwo, you can use this method block

const getTeams = () => {
  const teamSize = Math.ceil(playersArr.length / 2);

  const teamOne = playersArr.slice(0, teamSize);
  const teamTwo = playersArr.slice(teamSize);

  teams.push(teamOne, teamTwo);

}
  • Related