Shuffle An Array (JavaScript)

function shuffleArray(array) {  let currentIndex = array.length;
let temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
};
return array;};

BONUS

If we are trying to combine a couple of arrays and shuffle them, we just need to add and change couple lines of code.

function shuffleArray(array1, array2) {  let newArray = [];
newArray.push(...array1, ...array2);
let currentIndex = newArray.length;
let temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

temporaryValue = newArray[currentIndex];
newArray[currentIndex] = newArray[randomIndex];
newArray[randomIndex] = temporaryValue;
};
return newArray;};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Joseph Perez

Joseph Perez

I am a Jr. Web Developer, coding bootcamp graduate, and an ex-pro gamer.