shuffle array in javascript

How to Shuffle Array in JavaScript

JavaScript arrays are powerful data structures used by many developers and organizations, and offer plenty of useful features. Sometimes you may need to shuffle or randomize arrays in JavaScript. In other words, you may need to rearrange the array items in a random order, without creating or deleting any elements. In this article, we will learn how to shuffle array in JavaScript. This is often used by web developers to introduce an element of spontaneity in user experience. For example, you can use it to randomize the images in a gallery. It is also useful if you want to develop browser-based card games.


How to Shuffle Array in JavaScript

Let us say you have the following array in JavaScript.

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

To shuffle an array, we will use random() function in JavaScript. It returns a random floating point number between 0 and 1, excluding 1.

Here is a simple JS function to shuffle an array. It accepts array to be shuffled, as input parameter.

function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

Here is how you call it. It will shuffle the array in place, that is, it will modify the existing array, instead of shuffling a copy.

shuffle(arr) //[2, 1, 3, 4, 5]

Please note, every time you call the above function, you will most likely get a different output.

Let us look at the above function in detail. We use a for loop to traverse the array from last to the first element. We maintain the loop counter in variable i. In each iteration we calculate a random index j using the loop counter i. To do this, we basically use Math.random() function to get random floating point number and multiply it with (i+1), where i is the current value of for loop counter. Then we swap the array elements located at index i and j. This function uses the Fisher-Yates Shuffling algorithm.

You can also use the following function in browsers that support ES6 standard,

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

If you want to create a prototype for arrays, you can create it using the following code.

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

In the above case, you can directly call the shuffle function on each array on your webpage/website, as shown below.

arra.shuffl()

In this article, we have learnt how to shuffle arrays in JavaScript.

Also read:

How to Dynamically Create Variables in Python
How to Login to PostgreSQL Without Password
How to Store PostgreSQL Output to File
How to Get Row Count for All Tables in MySQL
How to Get Row Count for All Tables in PostgreSQL

Leave a Reply

Your email address will not be published.