Fisher-Yates shuffle

This is what you need for card games! The Fisher-Yates (or Knuth) shuffle ensures that all permutations of the set are equally likely (it’s unbiased).

Here’s the code in ES6 JavaScript, using a function that has an array a passed to it. When it comes to swapping the array elements there are various tricky ways of doing it, but I prefer to just do it in the most obvious way.

function shuffle(a) {
  for (let i = a.length - 1; i >= 1; i--) {
    let j = Math.floor(Math.random()*(i + 1));
    let tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;