home ~ projects ~ socials

Shuffle An Array

NOTE: This mutates the original array

Shuffle a JavaScript array with:

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

// Then
var arr = ['a', 'b', 'c', 'd', 'e', 'f',', 'g'];
shuffleArray(arr);
console.log(arr);
-- end of line --

References