Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Shuffle An Array

NOTE: This mutates the original array

Shuffle a JavaScript array with:

Code

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