Pavel Komiagin

1 min readHow to shuffle a JavaScript array

Every programmer can face the challenge of array shuffling. Of course, sometimes it is possible to use a library (e.g. underscore). But it is useful also to have the snippets for this task.

Shuffle that modifies a given array:

The array isn’t a primitive so Arrays are passed by reference. It means that array passed as a parameter will be changed when we will modify it inside the function:

// Initial array will be changed after shuffle
function mutableShuffle(arr) {
  var j;
  var temp
  
  for (var i = 0, max = arr.length; i < max; i++) {
    j = Math.floor(Math.random() * max);
    temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  
  return arr;
}

Shuffle that don’t modify a given array:

The function above doesn’t modify a given array. It creates, fills and returns a new array:

// Initial array will NOT be changed after shuffle
function immutableShuffle(arr) {
  var result = [];
  var j;
  var temp;
  
  for (var i = 0, max = arr.length; i < max; i++) {
    j = Math.floor(Math.random() * max);
    temp = arr[i];
    result[i] = arr[j];
    result[j] = temp;
  }
  
  return result;
}

How to use:

var mutableArr = [1, 2, 3];
console.log(mutableShuffle(mutableArr));
console.log(mutableArr); // will be changed

var immutableArr = [1, 2, 3];
console.log(immutableShuffle(immutableArr));
console.log(immutableArr); // will NOT be changed

You can try and modify it on codepen.

Leave a Reply

avatar
  Subscribe  
Notify of