JavaScript

How to randomize (shuffle) an array in Javascript

In this tutorial, we are going to see how to randomize (shuffle) an array in Javascript. Although many programming languages such as PHP and Ruby have built-in methods for randomizing arrays, while JavaScript does not have such a method for randomizing arrays.

So we are going to implement our own function to randomize an array.
 

Example :
Input:
[9, 4, 12, 3, 10]

Output:
[3, 9, 10, 12, 4]
 

How to randomize (shuffle) an array in Javascript

We will use Fisher’s algorithm to shuffle the array.

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

var arr = [9, 4, 12, 3, 10];
arr = randomize(arr);
console.log(arr);

Output:

[9, 3, 12, 10, 4]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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