mardi 25 septembre 2018

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

have been stuck on this for some time now. Working on React project for Table Tennis Game Generator. Struggling to find a solution to randomly shuffle an array of names, that have been entered by the user. It will not even console.log anything! Many thanks.

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;




Aucun commentaire:

Enregistrer un commentaire