Shuffle An Array

January - 2022

NOTE: This mutates the original array

Shuffle a JavaScript array with:

function shuffle(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]
      ]
  }

  return array;
}

// Then
var arr = ['a', 'b', 'c', 'd', 'e', 'f',', 'g'];
shuffle(arr);
console.log(arr);

via: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array