Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How can i apply the "shuffle" method to my players array so i can get random players in the two teams?
Tried couple of things but at this point i'm breaking the code.

My code :
```
let playersArr = []
const addPlayer = document.getElementById('input')
const btnAddPlayer = document.getElementById('add-player')
const players = document.getElementById('players')


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 = '';
  trashButton.classList.add('fa')
  newPlayer.appendChild(trashButton)


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

  trashButton.addEventListener('click', () => {
    players.removeChild(newPlayer)
  })

}
btnAddPlayer.addEventListener('click', (e) => {
  e.preventDefault()
  newPlayer()
  input.value = ''
})

const player = document.querySelectorAll('player')
const genBtn = document.getElementById('gen-btn')
const teamSheet = document.getElementById('teamsheet')

const teams = [];
const nrTeams = 2;


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

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

  teams.push(teamOne, teamTwo);
```


What I have tried:

Tried Math.random() on getTeams function but failed.
Posted
Updated 29-Sep-22 0:38am
Comments
Richard MacCutchan 29-Sep-22 6:14am    
"Tried Math.random() on getTeams function but failed."
Sorry, we cannot guess what "failed" means.
Member 15782660 29-Sep-22 11:39am    
Aplogies, forgot to paste the code.
I was going on this route:

const shufflePl = (playersArr) => {
playersArr.sort(() => Math.random() - 0.5)
shufflePl(playersArr)
}

Uncaught TypeError: Cannot read properties of undefined (reading 'sort')
at shufflePl (script.js:64:14)
at HTMLButtonElement.<anonymous> (script.js:132:3)
shufflePl @ script.js:64
(anonymous) @ script.js:132

..but didn't managed to integrate it.

1 solution

You might shuffle the array (see, for instance https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array[^]) and then slice it.

Since the proposed array-shuffling algorithm is really simple, you may also modify it in order to pick, on-the-fly, the players of the first team from the array. The remaining players will go directly in the second team.
 
Share this answer
 
Comments
Member 15782660 29-Sep-22 6:31am    
Thank you so much
CPallini 29-Sep-22 7:19am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900