shuffle array in javascript

How to Shuffle Array in JavaScript

JavaScript allows you to work with arrays of strings, objects and other data types. Sometimes you may need to randomize the order of elements in your array. In other words, you may need to shuffle array in JavaScript. In this article, we will learn how to do this.


How to Shuffle Array in JavaScript

Here are the steps to shuffle array in JavaScript. Let us say you have the following array.

var arr1 = ["a", "b", "c", "d"];

Here is a simple function to shuffle array in JavaScript.

function shuffle(array) {
  let currentIndex = array.length,  randomIndex;

  // While there remain elements to shuffle.
  while (currentIndex != 0) {

    // Pick a remaining element.
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }

  return array;
}

// Used like so
var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

The above function makes use of Knuth Shuffle Algorithm.

In the above code, we set a variable currentIndex to the length of array. We also set randomIndex variable to a random index derived from currentIndex. We swap array elements at the two positions indicated by currentIndex and randomIndex variables. Then we decrement the currentIndex variable by 1. We update the randomIndex value based on updated currentIndex value. We swap the two elements at currentIndex and randomIndex positions once again. We do this until currentIndex is not equal to zero. By then, you entire array would be shuffled.

You can use this function to shuffle any kind of array, since it works based on indexes and does not depend on the element values or data types.

For example, you can even use the above function on the following JavaScript array consisting of different types of data types.

var unshuffled = ['hello', 'a', 't', 'q', 1, 2, 3, {cats: true}]

You can modify and include this function in your web page or JavaScript library to simplify shuffling.

Also read:

How to Remove Local Time zone from Date in JavaScript
How to Format Date to MMDDYYYY in JavaScript
How to Copy to Clipboard in JavaScript
How to Get Query String Values in JavaScript
How to Check if Object is Empty in JavaScript

Leave a Reply

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