简体   繁体   English

从现有数组的值创建新数组

[英]Create new arrays from values of an existing array

I have an array with names我有一个名称数组

const players = ['name1','name2','name3','name4','name5','name6','name7','name8'];

const teams = players.length / 2; // -> 4 teams

I want to make teams of 2 people (randomly chosen) and make new arrays from the results -> team我想组成 2 人的团队(随机选择)并从结果中制作新的数组 -> 团队

function createTeams() {
  for (let i = 0; i < teams; i++) {
    for (let x = 0; x < 2; x++) {
      // get a random player
      selectedPlayer = players[Math.floor(Math.random() * players.length)];
      console.log('Selected Player will be added to a team: ', selectedPlayer);

      // delete this player from the array
      while (players.indexOf(selectedPlayer) !== -1) {
        players.splice(players.indexOf(selectedPlayer), 1);
      }

      // add this player to a new array
      //?????
    }
  }
}

Anyone knows how to do this?任何人都知道如何做到这一点?

You can define a new Array which will contains the teams where you push the two players.您可以定义一个新数组,其中将包含您推动两名球员的球队。

Note that it's better to pass the players array as a parameters of the function and make a swallow copy of it so it won't modify the player array.请注意,最好将玩家数组作为函数的参数传递并对其进行复制,这样它就不会修改玩家数组。

 const players = ['name1','name2','name3','name4','name5','name6','name7','name8']; function createTeams(players) { const playersLeft = [...players] const newTeams = [] const nbTeams = players.length / 2 for (let i=0; i<nbTeams; i++){ const player1 = playersLeft.splice(Math.floor(Math.random()*playersLeft.length),1)[0] const player2 = playersLeft.splice(Math.floor(Math.random()*playersLeft.length),1)[0] newTeams.push([player1, player2]) } return newTeams } console.log(createTeams(players))

Edit : Improve version using a nbPlayerPerTeam parameter编辑:使用nbPlayerPerTeam参数改进版本

 const players = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8']; function createTeams(players, nbPlayerPerTeam) { const playersLeft = [...players] const newTeams = [] const nbTeams = players.length / nbPlayerPerTeam for (let i = 0; i < nbTeams; i++) { const players = [] for (let j = 0; j < nbPlayerPerTeam; j++) { const player = playersLeft.splice(Math.floor(Math.random() * playersLeft.length), 1)[0] players.push(player) } newTeams.push(players) } return newTeams } console.log(createTeams(players, 3))

function pickTeams(array, teamSize) {

  // Shuffle array, make a copy to not alter original our original array
  const shuffled = [...array].sort( () => 0.5 - Math.random());

  const teams = [];
  // Create teams according to a team size
  for (let i = 0; i < shuffled.length; i += teamSize) {
    const chunk = shuffled.slice(i, i + teamSize);
    teams.push(chunk);
  }
  
  return teams;
  
}

const players = ['name1','name2','name3','name4','name5','name6','name7','name8'];

const teams = pickTeams(players, 2);

 const players = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8']; // Divide data by length const divide = (arr, n) => arr.reduce((r, e, i) => (i % n ? r[r.length - 1].push(e) : r.push([e])) && r, []); const shuffle = (arr) => { // Deep copy an array using structuredClone const array = structuredClone(arr); let currentIndex = array.length, randomIndex; // While there remain elements to shuffle while (currentIndex != 0) { // Pick a remaining element randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // And swap it with the current element [array[currentIndex], array[randomIndex]] = [ array[randomIndex], array[currentIndex] ]; } return array; } // Shuffle players const shuffled = shuffle(players); // Set a number of people in a team const groups = divide(shuffled, players.length / 2); groups.forEach((team, i) => console.log(`team ${i+1}`, JSON.stringify(team)));

Check this updated code, I hope it will work for you.检查这个更新的代码,我希望它对你有用。 Just create two dimensional array and push players.只需创建二维数组并推送玩家。

    const players = ['name1','name2','name3','name4','name5','name6','name7','name8'];
    let multi_team=new Array;     // new array for team of random 2 players
    const teams = players.length / 2; // -> 4 teams
    console.log(teams);
    createTeams();
    function createTeams() {
        for (let i = 0; i < teams; i++) {
            multi_team[i]= new Array;
            for (let x = 0; x < 2; x++) {
                // get a random player
                selectedPlayer = players[Math.floor(Math.random() * players.length)];
                multi_team[i][x]=selectedPlayer;
                 // delete this player from the array
                while (players.indexOf(selectedPlayer) !== -1) {
                    players.splice(players.indexOf(selectedPlayer), 1);
                }

            }
        }
        console.log(multi_team);
    }

To differ from previous answers, this is a dynamic way to do it, so you don't care if there are 5 teams or 2, 10 players or 500.与以前的答案不同,这是一种动态的方式,所以你不在乎是 5 支球队还是 2、10 名球员或 500 名球员。

 const players = ['j1', 'j2', 'j3', 'j4', 'j5', 'j6', 'j7', 'j8']; const organizeTeams = (numberOfTeams, players) => { var teams = []; // Clone the array to avoid mutations const freePlayers = [...players]; // How many players will play per team const playersPerTeam = Math.floor(players.length / numberOfTeams); // How many player won't have team const unorganizablePlayers = freePlayers.length % numberOfTeams; for (let t = 1; t <= numberOfTeams; t++) { teams = [...teams, pickRandomPlayers(freePlayers, playersPerTeam)]; } return { teams, playersPerTeam, unorganizablePlayers }; }; const pickRandomPlayers = (players, playersPerTeam) => { let pickedPlayers = []; for (let c = 1; c <= playersPerTeam; c++) { const index = Math.floor(Math.random() * (players.length - 1)); const player = players[index]; pickedPlayers = [...pickedPlayers, player]; // When we pick the player we remove it from the array to avoid duplicates. players.splice(index, 1); } return pickedPlayers; }; const championship = organizeTeams(3, players); console.log(`We have ${championship.teams.length} teams.`); championship.teams.forEach((team, index) => { console.log(`Team ${index + 1} players: ${team.join(',')}`); }); console.log( `There was no place to assign ${championship.unorganizablePlayers} players` );

 const players = [ 'name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8' ] const shuffled = players.sort((a, b) => 0.5 - Math.random()) const result = Array.from({ length: shuffled.length / 2 }, (_, i) => shuffled.slice(i * 2, i * 2 + 2)); console.log(result)

The OP needs (to implement ) a reliable shuffle and likewise an array's chunk functionality. OP 需要(实现)可靠的shuffle以及数组的chunk功能。

Then one just has to shuffle the provided players array (or a shallow copy of the latter) and to divide the array of randomly ordered player items into chunk s, each of custom provided length.然后只需对提供的players器数组(或后者的浅拷贝)进行洗牌,并将随机排序的播放器项目数组划分为,每个块都是自定义提供的长度。

 function shuffleArray(arr) { let idx; let count = arr.length; while (--count) { idx = Math.floor(Math.random() * (count + 1)); [arr[idx], arr[count]] = [arr[count], arr[idx]]; } return arr; } function createListOfChunkLists(arr, chunkLength = 0) { chunkLength = Math.max(0, chunkLength); return (chunkLength === 0 && []) || arr.reduce((list, item, idx) => { if (idx % chunkLength === 0) { list.push([ item ]); } else { list[list.length - 1].push(item); // `at` still not supported by safari. // list.at(-1).push(item); } return list; }, []); } // ... OP ... I have an array with names const players = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8']; // ... OP ... I want to make teams of 2 people (randomly chosen) // and make new arrays from the results -> team const teams = createListOfChunkLists( shuffleArray([...players]), 2 ); console.log({ teams, players }); console.log({ teams: createListOfChunkLists( shuffleArray([...players]), 2 ), players }); console.log({ teams: createListOfChunkLists( shuffleArray([...players]), 4 ), players });
 .as-console-wrapper { min-height: 100%!important; top: 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM