Skip to content

Generate two equal arrays of objects by key value

I have an array of players:

const players = [
  { nickName: 'John', level: 5 },
  { nickName: 'Doe', level: 4 },
  { nickName: 'James', level: 4 },
  { nickName: 'Moses', level: 5 },
  { nickName: 'Chris', level: 3 },
  { nickName: 'Dan', level: 3 },
]

I would like to generate two new random arrays called teamA and teamB , but I want those teams to be equal by players level.

for example:

const teamA = [
  { nickName: 'John', level: 5 },
  { nickName: 'Doe', level: 4 },
  { nickName: 'Dan', level: 3 },
]

const teamB = [
  { nickName: 'Moses', level: 5 },
  { nickName: 'James', level: 4 },
  { nickName: 'Chris', level: 3 },
]

I did manage to create two random arrays when I had array of strings without player’s level but now after I turned the array into array of objects I have no idea how to continue from here.

Any help would be appreciated.

Answer

We can do this with a simple enough approach.

Create a loop assigning players to the teams, one to each team for every round of the loop.

For team A, we pick a random player, then we assign a random player of the same level to team B.

Once the list of players is empty, we’re done.

const players = [
  { nickName: 'John', level: 5 },
  { nickName: 'Doe', level: 4 },
  { nickName: 'James', level: 4 },
  { nickName: 'Moses', level: 5 },
  { nickName: 'Chris', level: 3 },
  { nickName: 'Dan', level: 3 },
]

function takeRandomPlayer(arr, level) {
    let indexes = arr.reduce((acc, player, i) => {
        if (player.level === level || !level) acc.push(i);
        return acc;
    }, []);
    let index = indexes[Math.floor(Math.random()*indexes.length)];
    return arr.splice(index, 1)[0];
}

function createRandomTeams(players) {
    let teams = { teamA: [], teamB: [] };
    do {
        let playerA = takeRandomPlayer(players);
        teams.teamA.push(playerA);
        teams.teamB.push(takeRandomPlayer(players, playerA.level));
    } while (players.length);
    return teams;
}

const teams = createRandomTeams(players);
console.log(teams);
.as-console-wrapper { max-height: 100% !important; top: 0; }