How to randomize (shuffle) a JavaScript array?

How to randomize (shuffle) a JavaScript array? 1

In this post, we will write a function to randomize a JavaScript array.

Problem

Suppose we have an array of integer, how to randomize this array?

var arr = [1, 2, 3, 4, 5];

=> [3, 5, 4, 1, 2]  // a possible result

Solution with Fisher-Yates algorithm

As explained in the post of Random Number, there is a Fisher-Yates shuffling algorithm to solve this task.

Durstenfeld shuffle is a variant of Fisher-Yates algorithm. The time complexity is O(N).

function shuffle_array(array) {
  var cur_idx = array.length;

  // While there remain elements to shuffle...
  while (0 !== cur_idx) {
    // Pick a remaining element...
    var rand_idx = Math.floor(Math.random() * cur_idx);
    cur_idx -= 1;

    // And swap it with the current element.
    var tmp = array[cur_idx];
    array[cur_idx] = array[rand_idx];
    array[rand_idx] = tmp;
  }
  return array;
}

// Usage of shuffle
var arr = [1, 2, 3, 4, 5, 6];
arr = shuffle(arr);
console.log(arr);

Make it shorter

function shuffle_array(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
}

If you code with ES6/ECMAScript 2015(which allow use to assign two variables at once), the code will be much shorter:

function shuffle_array(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}
Last Updated on

Leave a Reply

Your email address will not be published. Required fields are marked *