Saturday, May 23, 2015

JavaScript - shuffle an array, mix up array elements randomly

Mix up (shuffle) array JavaScript function is taken from here:
Fisher–Yates Shuffle http://bost.ocks.org/mike/shuffle/
function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

No comments: