如何随机打乱包含名称字符串的数组?

How do I randomly shuffle an array, containing strings of names?

现在已经坚持了一段时间。为 Table Tennis Game Generator 开发 React 项目。努力寻找一种解决方案来随机排列用户输入的一组名称。它甚至不会 console.log 任何东西!非常感谢。

import React, { Fragment } from "react";

const FixturesList = playerNamesArray => {
    let shuffledPlayers = [...playerNamesArray];

    let arr1 = shuffledPlayers.slice(); // copy array
    let arr2 = shuffledPlayers.slice(); // copy array again

    arr1.sort(function() {
       return 0.5 - Math.random();
    }); // shuffle arrays
    arr2.sort(function() {
      return 0.5 - Math.random();
    });

    while (arr1.length) {
        let player1 = arr1.pop(), // get the last value of arr1
        player2 = arr2[0] === player1 ? arr2.pop() : arr2.shift();
        //        ^^ if the first value is the same as name1,
        //           get the last value, otherwise get the first
        console.log(player1 + " gets " + player2);
    }

    return (
        <Fragment>
             <section>
                 <h1>Fixtures</h1>
             </section>
        </Fragment>
    );
};

export default FixturesList;

我喜欢将 .sortMath.random

一起使用
const players = ['John', 'Jack', 'Anne', 'Marry', 'Mike', 'Jessica'];

players.sort(() => 0.5 - Math.random());

const pairs = [];

// as we need at least players to form a pair
while (players.length >= 2) { 
  const pair = [players.pop(), players.pop()];

  // Current pair
  console.log('Single pair', pair);

  // Save current pair
  pairs.push(pair);
}

// All pairs
console.log('All pairs', pairs);

我猜你已经知道了,但是随机 return 0 和 1 之间的数字(不包括 1)所以这个排序函数将随机 return -0.5 和 0.5 之间的数字来洗牌数组。

Pop 将 return 数组中的最后一项并将其从数组中删除。我们弹出两次以获得一对。

希望对您有所帮助!


接评论。

为了渲染它,我会创建一个组件,然后将 pairs 传递给它。这是必不可少的 React,也是您将经常做的事情。

import React from 'react';

component Pairs extends React.component
  renderPairs() {
    // pass pairs as prop
    return this.props.pairs.map(pair => {
      return (
        <li key={ pair.join('-') }>
          { pair.join(' vs ') }
        </li>
      )
    });
  }

  return (
    <ul>
      { this.renderPairs() }
    </ul>
  )
}

// Use it like this
// <Pairs pairs={ pairs } />